Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "runtime"
- )
- // Tune me!
- const batchSize = 5000
- type batchResult struct {
- start uint32
- primes []uint32
- }
- func main() {
- // Tune me!
- runtime.GOMAXPROCS(runtime.NumCPU())
- fmt.Println("1")
- fmt.Println("2")
- // Tune me!
- numJobs := runtime.NumCPU()
- results := make(chan batchResult, numJobs)
- jobs := make(chan uint32)
- for i := 0; i < numJobs; i++ {
- go func() {
- for start := range jobs {
- ps := make([]uint32, 0, 5)
- next:
- for x, end := start, start+batchSize; x < end; x += 2 {
- if x%2 == 0 {
- continue
- }
- for j := uint32(3); j < x; j += 2 {
- if x%j == 0 {
- continue next
- }
- }
- ps = append(ps, x)
- }
- results <- batchResult{start: start, primes: ps}
- }
- }()
- }
- go func() {
- for i := uint32(3); ; i += batchSize {
- jobs <- i
- }
- }()
- // result batches do not always arrive in order
- // so hold some back if needed.
- expected := uint32(3)
- hold := make([]batchResult, 0, numJobs)
- for result := range results {
- if result.start == expected {
- out:
- for _, prime := range result.primes {
- fmt.Printf("%d\n", prime)
- }
- expected += batchSize
- // check if follow up is hold.
- for i := range hold {
- if hold[i].start == expected {
- result = hold[i]
- copy(hold[i:], hold[i+1:])
- hold = hold[:len(hold)-1]
- goto out
- }
- }
- } else { // hold back
- hold = append(hold, result)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement