Rémy Oudompheng | fc3797a | 2012-02-22 00:19:59 +0100 | [diff] [blame] | 1 | // build |
| 2 | |
Robert Griesemer | 0d1e90b | 2008-03-11 18:07:22 -0700 | [diff] [blame] | 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 | |
Rob Pike | 80a9783 | 2012-02-24 11:48:19 +1100 | [diff] [blame] | 7 | // Test basic concurrency: the classic prime sieve. |
| 8 | // Do not run - loops forever. |
| 9 | |
Rob Pike | 2fdbf0d | 2008-07-12 13:56:33 -0700 | [diff] [blame] | 10 | package main |
Robert Griesemer | 0d1e90b | 2008-03-11 18:07:22 -0700 | [diff] [blame] | 11 | |
| 12 | // Send the sequence 2, 3, 4, ... to channel 'ch'. |
Russ Cox | 839a684 | 2009-01-20 14:40:40 -0800 | [diff] [blame] | 13 | func Generate(ch chan<- int) { |
Rob Pike | 3310192 | 2008-07-15 20:52:07 -0700 | [diff] [blame] | 14 | for i := 2; ; i++ { |
Rob Pike | 4f61fc9 | 2010-09-04 10:36:13 +1000 | [diff] [blame] | 15 | ch <- i // Send 'i' to channel 'ch'. |
Rob Pike | 3310192 | 2008-07-15 20:52:07 -0700 | [diff] [blame] | 16 | } |
Robert Griesemer | 0d1e90b | 2008-03-11 18:07:22 -0700 | [diff] [blame] | 17 | } |
| 18 | |
| 19 | // Copy the values from channel 'in' to channel 'out', |
| 20 | // removing those divisible by 'prime'. |
Russ Cox | 839a684 | 2009-01-20 14:40:40 -0800 | [diff] [blame] | 21 | func Filter(in <-chan int, out chan<- int, prime int) { |
Rob Pike | 3310192 | 2008-07-15 20:52:07 -0700 | [diff] [blame] | 22 | for { |
Rob Pike | 4f61fc9 | 2010-09-04 10:36:13 +1000 | [diff] [blame] | 23 | i := <-in // Receive value of new variable 'i' from 'in'. |
| 24 | if i%prime != 0 { |
| 25 | out <- i // Send 'i' to channel 'out'. |
Rob Pike | 3310192 | 2008-07-15 20:52:07 -0700 | [diff] [blame] | 26 | } |
| 27 | } |
Robert Griesemer | 0d1e90b | 2008-03-11 18:07:22 -0700 | [diff] [blame] | 28 | } |
| 29 | |
| 30 | // The prime sieve: Daisy-chain Filter processes together. |
Russ Cox | 839a684 | 2009-01-20 14:40:40 -0800 | [diff] [blame] | 31 | func Sieve() { |
Rob Pike | 4f61fc9 | 2010-09-04 10:36:13 +1000 | [diff] [blame] | 32 | ch := make(chan int) // Create a new channel. |
| 33 | go Generate(ch) // Start Generate() as a subprocess. |
Rob Pike | 3310192 | 2008-07-15 20:52:07 -0700 | [diff] [blame] | 34 | for { |
Rob Pike | 4f61fc9 | 2010-09-04 10:36:13 +1000 | [diff] [blame] | 35 | prime := <-ch |
| 36 | print(prime, "\n") |
| 37 | ch1 := make(chan int) |
| 38 | go Filter(ch, ch1, prime) |
Rob Pike | 3310192 | 2008-07-15 20:52:07 -0700 | [diff] [blame] | 39 | ch = ch1 |
| 40 | } |
Robert Griesemer | 0d1e90b | 2008-03-11 18:07:22 -0700 | [diff] [blame] | 41 | } |
| 42 | |
Rob Pike | 2fdbf0d | 2008-07-12 13:56:33 -0700 | [diff] [blame] | 43 | func main() { |
Rob Pike | 74dd0ab | 2009-08-17 13:30:22 -0700 | [diff] [blame] | 44 | Sieve() |
Robert Griesemer | 0d1e90b | 2008-03-11 18:07:22 -0700 | [diff] [blame] | 45 | } |