github.com/likebike/go--@v0.0.0-20190911215757-0bd925d16e96/go/doc/play/sieve.go (about) 1 // A concurrent prime sieve 2 3 package main 4 5 import "fmt" 6 7 // Send the sequence 2, 3, 4, ... to channel 'ch'. 8 func Generate(ch chan<- int) { 9 for i := 2; ; i++ { 10 ch <- i // Send 'i' to channel 'ch'. 11 } 12 } 13 14 // Copy the values from channel 'in' to channel 'out', 15 // removing those divisible by 'prime'. 16 func Filter(in <-chan int, out chan<- int, prime int) { 17 for { 18 i := <-in // Receive value from 'in'. 19 if i%prime != 0 { 20 out <- i // Send 'i' to 'out'. 21 } 22 } 23 } 24 25 // The prime sieve: Daisy-chain Filter processes. 26 func main() { 27 ch := make(chan int) // Create a new channel. 28 go Generate(ch) // Launch Generate goroutine. 29 for i := 0; i < 10; i++ { 30 prime := <-ch 31 fmt.Println(prime) 32 ch1 := make(chan int) 33 go Filter(ch, ch1, prime) 34 ch = ch1 35 } 36 }