Created
February 1, 2016 10:39
-
-
Save esimov/bcfb195a46e1b955fdfc to your computer and use it in GitHub Desktop.
Concurrent Prime Sieve using goroutines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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