The Go Programming Language

Source file doc/progs/sieve.go

     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	package main
     6	
     7	import "fmt"
     8	
     9	// Send the sequence 2, 3, 4, ... to channel 'ch'.
    10	func generate(ch chan int) {
    11		for i := 2; ; i++ {
    12			ch <- i // Send 'i' to channel 'ch'.
    13		}
    14	}
    15	
    16	// Copy the values from channel 'in' to channel 'out',
    17	// removing those divisible by 'prime'.
    18	func filter(in, out chan int, prime int) {
    19		for {
    20			i := <-in // Receive value of new variable 'i' from 'in'.
    21			if i%prime != 0 {
    22				out <- i // Send 'i' to channel 'out'.
    23			}
    24		}
    25	}
    26	
    27	// The prime sieve: Daisy-chain filter processes together.
    28	func main() {
    29		ch := make(chan int)       // Create a new channel.
    30		go generate(ch)            // Start generate() as a goroutine.
    31		for i := 0; i < 100; i++ { // Print the first hundred primes.
    32			prime := <-ch
    33			fmt.Println(prime)
    34			ch1 := make(chan int)
    35			go filter(ch, ch1, prime)
    36			ch = ch1
    37		}
    38	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.