From 12cf4f79ff7fc56d4b5ba3b7ce2debd1cb46d27c Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Tue, 13 Jul 2021 00:13:44 +0200 Subject: [PATCH] Mark non-primes in parallel goroutines --- eratosthenes_parallel.go | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/eratosthenes_parallel.go b/eratosthenes_parallel.go index b327807..517e34a 100644 --- a/eratosthenes_parallel.go +++ b/eratosthenes_parallel.go @@ -3,15 +3,27 @@ package main import ( "fmt" "os" + "runtime" "strconv" + "sync" "time" ) +var markGroup sync.WaitGroup + +func markMultiples(sieve []uint64, i int64, n0, n1 int64) { + for j := n0; j < n1; j += 2 * i { + sieve[j>>7] |= 1 << ((j & 0x7F) >> 1) + } + markGroup.Done() +} + func main() { n, err := strconv.ParseInt(os.Args[1], 10, 64) if err != nil { panic(err) } + nCpus := int64(runtime.NumCPU()) t0 := time.Now() sieve := make([]uint64, (n>>7)+1) var found int64 @@ -21,9 +33,16 @@ func main() { for i = 3; i < n; i += 2 { if (sieve[i>>7] & (1 << ((i & 0x7F) >> 1))) == 0 { found++ - for j := i * i; j < n; j += 2 * i { - sieve[j>>7] |= 1 << ((j & 0x7F) >> 1) + + p := nCpus + var jnext int64 + for j := i * i; j < n; j = jnext { + jnext = ((n-j)/(2*i)/p+1)*(2*i) + j + markGroup.Add(1) + go markMultiples(sieve, i, j, jnext) + p-- } + markGroup.Wait() } } d := time.Since(t0)