Created
August 15, 2016 21:28
-
-
Save phagenlocher/5982b3b0119638d0443fdd96b2a1270b to your computer and use it in GitHub Desktop.
Generating prime numbers with go routines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "math" | |
| "math/rand" | |
| "time" | |
| ) | |
| func generate_prime(min int, max int, result chan int) { | |
| MainLoop: | |
| // Generate number between min and max | |
| x := (rand.Int() % (max - min + 1)) + min | |
| // Test for prime | |
| for i := 2; i <= int(math.Sqrt(float64(x))); i++ { | |
| if x%i == 0 { | |
| // If its divisible, go to function start | |
| goto MainLoop | |
| } | |
| } | |
| // Send result via chan | |
| result <- x | |
| } | |
| func main() { | |
| // Number of routines to start | |
| num_routines := 100 | |
| // Buffered chan to get results on routines | |
| result := make(chan int, num_routines) | |
| // Seeding RNG with current time | |
| rand.Seed(time.Now().Unix()) | |
| // Starting routines | |
| for i := 0; i < num_routines; i++ { | |
| go generate_prime(100000, 1000000000, result) | |
| } | |
| // Waiting for routines to finish | |
| results := 0 | |
| for results < cap(result) { | |
| fmt.Println(<-result) | |
| results++ | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment