Source file test/chan/sieve1.go

     1  // run
     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 concurrency primitives: classical inefficient concurrent prime sieve.
     8  
     9  // Generate primes up to 100 using channels, checking the results.
    10  // This sieve consists of a linear chain of divisibility filters,
    11  // equivalent to trial-dividing each n by all primes p ≤ n.
    12  
    13  package main
    14  
    15  // Send the sequence 2, 3, 4, ... to channel 'ch'.
    16  func Generate(ch chan<- int) {
    17  	for i := 2; ; i++ {
    18  		ch <- i // Send 'i' to channel 'ch'.
    19  	}
    20  }
    21  
    22  // Copy the values from channel 'in' to channel 'out',
    23  // removing those divisible by 'prime'.
    24  func Filter(in <-chan int, out chan<- int, prime int) {
    25  	for i := range in { // Loop over values received from 'in'.
    26  		if i%prime != 0 {
    27  			out <- i // Send 'i' to channel 'out'.
    28  		}
    29  	}
    30  }
    31  
    32  // The prime sieve: Daisy-chain Filter processes together.
    33  func Sieve(primes chan<- int) {
    34  	ch := make(chan int) // Create a new channel.
    35  	go Generate(ch)      // Start Generate() as a subprocess.
    36  	for {
    37  		// Note that ch is different on each iteration.
    38  		prime := <-ch
    39  		primes <- prime
    40  		ch1 := make(chan int)
    41  		go Filter(ch, ch1, prime)
    42  		ch = ch1
    43  	}
    44  }
    45  
    46  func main() {
    47  	primes := make(chan int)
    48  	go Sieve(primes)
    49  	a := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
    50  	for i := 0; i < len(a); i++ {
    51  		if x := <-primes; x != a[i] {
    52  			println(x, " != ", a[i])
    53  			panic("fail")
    54  		}
    55  	}
    56  }
    57  

View as plain text