Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: bc2a1c3bc1
Fetching contributors…

Cannot retrieve contributors at this time

file 65 lines (56 sloc) 1.605 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
package main

import "fmt"

func main() {
    //A Channel to send integers to calculate
    integers := make(chan int64)

    //A channel for the factorial goroutine to send results to be displayed
    results := make(chan int64)
    done := make(chan bool) //Goroutine to calculate factorial

    go factorial(integers, results) //Goroutine to display results
    go display(results, done)

    //Generate integers and send them on the integer channel
    generateIntegers(integers)

    //Receive a value on the done channel and discard it
    //effectively blocking program termination until
    //communication occurs on this channel
    <-done
}

func factorial(c chan int64, results chan int64) {
    for {
        i, ok := <-c
            if !ok {
                // channel is closed, so we are done
                break
            }
        var fact int64
            fact = 1
            for {
                fact = fact * i
                    i = i - 1
                    if i <= 1 {
                        break
                    }
            }
        results <- fact
    }
    close(results)
}

func generateIntegers(c chan int64) {
    var x int64
        for x = 1; x < 11; x++ { c <- x
        }
    //Close the channel to signify that we //have no more values to send
    close(c)
}

func display(results chan int64, completed chan bool) {
    for {
        i, ok := <-results
            if !ok {
                // channel is closed, so we are done
                break
            }
        fmt.Println(i)
    }
    //Signify to main that we're done
    completed <- true
}
Something went wrong with that request. Please try again.