Last active
September 14, 2015 20:12
-
-
Save rogeriomarques/ca64b56d450388ad551a to your computer and use it in GitHub Desktop.
Simple pool worker example
This file contains 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" | |
) | |
func isPrime(n float64) bool { | |
max := int(math.Sqrt(n)) | |
for i := 2; i < max; i++ { | |
if int(n)%i == 0 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
jobscount := 1000000 | |
workers := 4 | |
pool := make(chan int) | |
done := make(chan int) | |
go func() { | |
for i := 0; i < jobscount; i++ { | |
pool <- i | |
} | |
}() | |
for i := 0; i < workers; i++ { | |
go worker(i, pool, done) | |
} | |
for i := 0; i < jobscount; i++ { | |
<-done | |
} | |
} | |
func worker(worker int, pool, done chan int) { | |
for jobid := range pool { | |
if isPrime(float64(jobid)) { | |
fmt.Printf("%v\n", jobid) | |
} | |
done <- jobid | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment