Last active
          September 15, 2015 10:20 
        
      - 
      
- 
        Save jmprusi/6527bf7d62f284c76a14 to your computer and use it in GitHub Desktop. 
    Simple pool worker example
  
        
  
    
      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" | |
| ) | |
| 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