Skip to content

Instantly share code, notes, and snippets.

@sudipidus
Created January 27, 2024 17:24
Show Gist options
  • Save sudipidus/2053387d9321c62b605ac00e3e6b4eec to your computer and use it in GitHub Desktop.
Save sudipidus/2053387d9321c62b605ac00e3e6b4eec to your computer and use it in GitHub Desktop.
parallel prime number sieve in golang
// Communication Sequential Process (CSP) - Tony Hoare
// Finding Prime numbers using sieve in parallel
package main
import "fmt"
func main() {
src := make(chan int)
go Generate(src)
for i := 0; i < 100; i++ {
prime := <-src
fmt.Println(prime)
dest := make(chan int)
go Filter(src, dest, prime)
src = dest
}
}
func Generate(ch chan<- int) {
for i := 2; ; i++ {
ch <- i
}
}
func Filter(src <-chan int, dest chan<- int, prime int) {
for i := range src { // loop over the values received in source channel
if i%prime != 0 {
dest <- i //send to destination channel
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment