ryochack
8/8/2013 - 7:25 AM

chansync_select.go

package main

import (
	"fmt"
)

func f(msg string, n int) (chan string, chan bool) {
	ch := make(chan string)
	done := make(chan bool)
	go func() {
		for i:=0; i<n; i++ {
			ch <- msg + " please!"
		}
		done <- true
	}()
	return ch, done
}

func main() {
	ch1, done1 := f("beer",  4)
	ch2, done2 := f("juice", 2)
	ch3, done3 := f("water", 1)

	count := 0
	L:
	for {
		select {
		case msg := <-ch1:
			fmt.Println(msg)
		case msg := <-ch2:
			fmt.Println(msg)
		case msg := <-ch3:
			fmt.Println(msg)
		case <-done1:
			count++
		case <-done2:
			count++
		case <-done3:
			count++
		}
		if (count > 2) {
			break L
		}
	}
	fmt.Println("exit")
}