Skip to content

Instantly share code, notes, and snippets.

@esimov
Created February 1, 2016 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esimov/bcfb195a46e1b955fdfc to your computer and use it in GitHub Desktop.
Save esimov/bcfb195a46e1b955fdfc to your computer and use it in GitHub Desktop.
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