Advertisement
Guest User

concurrentprime.go

a guest
Jun 6th, 2015
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.48 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. type batchResult struct {
  12.     start  uint32
  13.     primes []uint32
  14. }
  15.  
  16. func main() {
  17.  
  18.     // Tune me!
  19.     runtime.GOMAXPROCS(runtime.NumCPU())
  20.  
  21.     fmt.Println("1")
  22.     fmt.Println("2")
  23.  
  24.     // Tune me!
  25.     numJobs := runtime.NumCPU()
  26.  
  27.     results := make(chan batchResult, numJobs)
  28.     jobs := make(chan uint32)
  29.  
  30.     for i := 0; i < numJobs; i++ {
  31.         go func() {
  32.             for start := range jobs {
  33.                 ps := make([]uint32, 0, 5)
  34.             next:
  35.                 for x, end := start, start+batchSize; x < end; x += 2 {
  36.                     if x%2 == 0 {
  37.                         continue
  38.                     }
  39.                     for j := uint32(3); j < x; j += 2 {
  40.                         if x%j == 0 {
  41.                             continue next
  42.                         }
  43.                     }
  44.                     ps = append(ps, x)
  45.                 }
  46.                 results <- batchResult{start: start, primes: ps}
  47.             }
  48.         }()
  49.     }
  50.  
  51.     go func() {
  52.         for i := uint32(3); ; i += batchSize {
  53.             jobs <- i
  54.         }
  55.     }()
  56.  
  57.     // result batches do not always arrive in order
  58.     // so hold some back if needed.
  59.     expected := uint32(3)
  60.     hold := make([]batchResult, 0, numJobs)
  61.  
  62.     for result := range results {
  63.         if result.start == expected {
  64.         out:
  65.             for _, prime := range result.primes {
  66.                 fmt.Printf("%d\n", prime)
  67.             }
  68.             expected += batchSize
  69.             // check if follow up is hold.
  70.             for i := range hold {
  71.                 if hold[i].start == expected {
  72.                     result = hold[i]
  73.                     copy(hold[i:], hold[i+1:])
  74.                     hold = hold[:len(hold)-1]
  75.                     goto out
  76.                 }
  77.             }
  78.         } else { // hold back
  79.             hold = append(hold, result)
  80.         }
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement