github.com/rsc/tmp@v0.0.0-20240517235954-6deaab19748b/gomaxprocs/sieve/sieve_test.go (about)

     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.
     4  
     5  // Test concurrency primitives: classical inefficient concurrent prime sieve.
     6  
     7  // Generate primes up to 100 using channels, checking the results.
     8  // This sieve consists of a linear chain of divisibility filters,
     9  // equivalent to trial-dividing each n by all primes p ≤ n.
    10  
    11  package sieve_test
    12  
    13  import "testing"
    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  var sieveOnce bool
    47  
    48  func BenchmarkSieve(b *testing.B) {
    49  	if sieveOnce {
    50  		b.Fatal("can only run once")
    51  	}
    52  	if b.N != 1 {
    53  		b.Fatal("can only run one iteration")
    54  	}
    55  	sieveOnce = true
    56  	primes := make(chan int)
    57  	go Sieve(primes)
    58  	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}
    59  	for i := 0; i < len(a); i++ {
    60  		if x := <-primes; x != a[i] {
    61  			println(x, " != ", a[i])
    62  			panic("fail")
    63  		}
    64  	}
    65  	for i := 0; i < 10000; i++ {
    66  		<-primes
    67  	}
    68  }