Advertisement
Guest User

concurrentprime.go

a guest
Jun 6th, 2015
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.83 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "runtime"
  6. )
  7.  
  8. // Tune me!
  9. const batchSize = 5000
  10.  
  11. func main() {
  12.  
  13.     // Tune me!
  14.     runtime.GOMAXPROCS(runtime.NumCPU())
  15.  
  16.     primes := make(chan uint32)
  17.     jobs := make(chan uint32)
  18.  
  19.     fmt.Println("1")
  20.     fmt.Println("2")
  21.  
  22.     // Tune me!
  23.     numJobs := runtime.NumCPU()
  24.  
  25.     for i := 0; i < numJobs; i++ {
  26.         go func() {
  27.             for x := range jobs {
  28.             next:
  29.                 for end := x + batchSize; x < end; x += 2 {
  30.                     if x%2 == 0 {
  31.                         continue
  32.                     }
  33.                     for j := uint32(3); j < x; j += 2 {
  34.                         if x%j == 0 {
  35.                             continue next
  36.                         }
  37.                     }
  38.                     primes <- x
  39.                 }
  40.             }
  41.         }()
  42.     }
  43.     highest := uint32(2)
  44.  
  45.     go func() {
  46.         for i := uint32(3); ; i += batchSize {
  47.             jobs <- i
  48.         }
  49.     }()
  50.  
  51.     for prime := range primes {
  52.         if prime > highest {
  53.             highest = prime
  54.             fmt.Printf("%d\n", prime)
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement