go sieve-of-eratosthenes
tags: learning go programming concurrency
content
-
sieve of eratosthenes
- give an array [2, infinity)
- the first element is prime, add to
prime_list - filter out elements that are the multiple of the first element
- generate a new array
- repeat 2~3, until
prime_listis desired length
-
with Go channels and concurrency
- component 1: a goroutine keeps writing into a channel
ch1, simulate an array input - main:
- reads
ch1(which is 2, prime) - creates new goroutine (new component) and passes in
ch1(after 2 is read) and 2(prime)
- reads
- component 2:
- a goroutine takes from
ch1, check if it’s a multiple ofprime - filters out multiples, and writes to
ch2
- a goroutine takes from
- main (repeats 2.1, 2.2):
- reads
ch2(which is the next primenext_prime) - creates new goroutine and passes in
ch2and thenext_prime
- reads
- component 1: a goroutine keeps writing into a channel
-
basically, how each goroutine writes to the channels is like creating new arrays
-
from Visualizing Concurrency in Go · divan’s blog, we can see each goroutine’s life time lasts until main finishes
draw this with excalidraw tbc
Iteration 1:
Generate -2→ [ch] → main reads here, prints 2
After iteration 1:
Generate -3→ [ch] → Filter(2) → [ch1] → main reads here, prints 3
^ ^---- ch1 is 3, (3%2!=0, 3 gets written to channel)
+----- previous prime is 2
After iteration 2:
Generate -4/5→ [ch] → Filter(2) → [ch1] → Filter(3) → [ch2] → main reads here, prints 5
^--- 4 gets dropped ^---- ch1 is 5, (5%2!=0, 5 gets written to channel)
+----- previous prime is 3
After iteration 3:
Generate → [ch] → Filter(2) → [ch1] → Filter(3) → [ch2] → Filter(5) → [ch3] → main reads here- NOTE: every newly generated number from
Generate()has gone through ALL go routines ever created until it gets filtered out