Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Concurrent Prime Sieve using goroutines
package main
import (
"fmt"
)
func main() {
prime := primes()
for {
fmt.Println(<-prime)
}
}
func generate() chan int {
in := make(chan int)
go func() {
for i := 2; ; i++ {
in <- i
}
}()
return in
}
func filter(in chan int, prime int) chan int {
out := make(chan int)
go func() {
for {
if i := <-in; i%prime != 0 {
out <- i
}
}
}()
return out
}
func primes() chan int {
out := make(chan int)
go func() {
ch := generate()
for {
prime := <-ch
ch = filter(ch, prime)
out <- prime
}
}()
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment