ryochack
8/8/2013 - 7:28 AM

chansync_waitgroup.go

package main

import (
	"fmt"
	"sync"
)

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

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

	var wg sync.WaitGroup

	reporter := func(ch chan string) {
		defer wg.Done()
		for msg := range ch {
			fmt.Println(msg)
		}
	}

	wg.Add(3)
	go reporter(ch1)
	go reporter(ch2)
	go reporter(ch3)
	wg.Wait()

	fmt.Println("exit")
}