Home | History | Annotate | Download | only in test
      1 // build
      2 
      3 // Copyright 2009 The Go Authors. All rights reserved.
      4 // Use of this source code is governed by a BSD-style
      5 // license that can be found in the LICENSE file.
      6 
      7 // Test basic concurrency: the classic prime sieve.
      8 // Do not run - loops forever.
      9 
     10 package main
     11 
     12 // Send the sequence 2, 3, 4, ... to channel 'ch'.
     13 func Generate(ch chan<- int) {
     14 	for i := 2; ; i++ {
     15 		ch <- i // Send 'i' to channel 'ch'.
     16 	}
     17 }
     18 
     19 // Copy the values from channel 'in' to channel 'out',
     20 // removing those divisible by 'prime'.
     21 func Filter(in <-chan int, out chan<- int, prime int) {
     22 	for {
     23 		i := <-in // Receive value of new variable 'i' from 'in'.
     24 		if i%prime != 0 {
     25 			out <- i // Send 'i' to channel 'out'.
     26 		}
     27 	}
     28 }
     29 
     30 // The prime sieve: Daisy-chain Filter processes together.
     31 func Sieve() {
     32 	ch := make(chan int) // Create a new channel.
     33 	go Generate(ch)      // Start Generate() as a subprocess.
     34 	for {
     35 		prime := <-ch
     36 		print(prime, "\n")
     37 		ch1 := make(chan int)
     38 		go Filter(ch, ch1, prime)
     39 		ch = ch1
     40 	}
     41 }
     42 
     43 func main() {
     44 	Sieve()
     45 }
     46