/*
* Collector, using a switch.
*/
package main
import (
"fmt"
"time"
"math/rand"
)
/*
* This function repeatedly sends values to the main, stopping when
* main asks it to.
*/
func generator(limit int, results chan<- int, term chan string) {
for {
select {
case <- term:
results <- -1
return
default:
results <- rand.Intn(limit) + 1
}
}
}
/*
* The main mostly starts the printer function, then waits for the message
* from the printer.
*/
func main() {
rand.Seed(time.Now().UnixNano())
// Channel to tell them to stop.
stopper := make(chan string,3)
// Start three and make channels for them.
results1 := make(chan int)
go generator(12,results1,stopper)
results2 := make(chan int)
go generator(20,results2,stopper)
results3 := make(chan int)
go generator(8,results3,stopper)
// Acculate results.
tot := 0
running := 3
stopped := false
for running > 0{
var got int
var which int
select {
case n := <- results1:
got = n
which = 1
case n := <- results2:
got = n
which = 2
case n := <- results3:
got = n
which = 3
}
if got >= 0 {
tot += got
fmt.Println("Got",got,"from",which,"giving",tot)
} else {
running--
fmt.Println("Worker",which,"shut down")
}
// If we've got enough, tell them all to stop.
if !stopped && (tot > 500) {
// Stop each goroutine.
for n := 1; n <= 3; n++ {
stopper <- "stop"
}
stopped = true
}
}
}