blob: 0cd120c548e368f3a8c741ad2aacbf459f768334 [file] [log] [blame]
Rémy Oudomphengfc3797a2012-02-22 00:19:59 +01001// build
2
Robert Griesemer0d1e90b2008-03-11 18:07:22 -07003// 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
Rob Pike80a97832012-02-24 11:48:19 +11007// Test basic concurrency: the classic prime sieve.
8// Do not run - loops forever.
9
Rob Pike2fdbf0d2008-07-12 13:56:33 -070010package main
Robert Griesemer0d1e90b2008-03-11 18:07:22 -070011
12// Send the sequence 2, 3, 4, ... to channel 'ch'.
Russ Cox839a6842009-01-20 14:40:40 -080013func Generate(ch chan<- int) {
Rob Pike33101922008-07-15 20:52:07 -070014 for i := 2; ; i++ {
Rob Pike4f61fc92010-09-04 10:36:13 +100015 ch <- i // Send 'i' to channel 'ch'.
Rob Pike33101922008-07-15 20:52:07 -070016 }
Robert Griesemer0d1e90b2008-03-11 18:07:22 -070017}
18
19// Copy the values from channel 'in' to channel 'out',
20// removing those divisible by 'prime'.
Russ Cox839a6842009-01-20 14:40:40 -080021func Filter(in <-chan int, out chan<- int, prime int) {
Rob Pike33101922008-07-15 20:52:07 -070022 for {
Rob Pike4f61fc92010-09-04 10:36:13 +100023 i := <-in // Receive value of new variable 'i' from 'in'.
24 if i%prime != 0 {
25 out <- i // Send 'i' to channel 'out'.
Rob Pike33101922008-07-15 20:52:07 -070026 }
27 }
Robert Griesemer0d1e90b2008-03-11 18:07:22 -070028}
29
30// The prime sieve: Daisy-chain Filter processes together.
Russ Cox839a6842009-01-20 14:40:40 -080031func Sieve() {
Rob Pike4f61fc92010-09-04 10:36:13 +100032 ch := make(chan int) // Create a new channel.
33 go Generate(ch) // Start Generate() as a subprocess.
Rob Pike33101922008-07-15 20:52:07 -070034 for {
Rob Pike4f61fc92010-09-04 10:36:13 +100035 prime := <-ch
36 print(prime, "\n")
37 ch1 := make(chan int)
38 go Filter(ch, ch1, prime)
Rob Pike33101922008-07-15 20:52:07 -070039 ch = ch1
40 }
Robert Griesemer0d1e90b2008-03-11 18:07:22 -070041}
42
Rob Pike2fdbf0d2008-07-12 13:56:33 -070043func main() {
Rob Pike74dd0ab2009-08-17 13:30:22 -070044 Sieve()
Robert Griesemer0d1e90b2008-03-11 18:07:22 -070045}