sieve1.go 915 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.package main
  4. package main
  5. import "fmt"
  6. // Send the sequence 2, 3, 4, ... to channel 'ch'.
  7. func generate(ch chan int) {
  8. for i := 2; ; i++ {
  9. ch <- i // Send 'i' to channel 'ch'.
  10. }
  11. }
  12. // Copy the values from channel 'in' to channel 'out',
  13. // removing those divisible by 'prime'.
  14. func filter(in, out chan int, prime int) {
  15. for {
  16. i := <-in // Receive value of new variable 'i' from 'in'.
  17. if i%prime != 0 {
  18. out <- i // Send 'i' to channel 'out'.
  19. }
  20. }
  21. }
  22. // The prime sieve: Daisy-chain filter processes together.
  23. func main() {
  24. ch := make(chan int) // Create a new channel.
  25. go generate(ch) // Start generate() as a goroutine.
  26. for {
  27. prime := <-ch
  28. fmt.Print(prime, " ")
  29. ch1 := make(chan int)
  30. go filter(ch, ch1, prime)
  31. ch = ch1
  32. }
  33. }