github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/hellogophers/sieve.go (about) 1 // +build ignore,OMIT 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 'src' to channel 'dst', 15 // removing those divisible by 'prime'. 16 func filter(src <-chan int, dst chan<- int, prime int) { 17 for i := range src { // Loop over values received from 'src'. 18 if i%prime != 0 { 19 dst <- i // Send 'i' to channel 'dst'. 20 } 21 } 22 } 23 // BREAK OMIT 24 // The prime sieve: Daisy-chain filter processes together. 25 func sieve() { 26 ch := make(chan int) // Create a new channel. 27 go generate(ch) // Start generate() as a subprocess. 28 for { 29 prime := <-ch 30 fmt.Print(prime, "\n") 31 ch1 := make(chan int) 32 go filter(ch, ch1, prime) 33 ch = ch1 34 } 35 } 36 37 func main() { 38 sieve() 39 }