sieve.go 762 B

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