Source

go-wise / multisync.go

/* Example on how to synchronize multiple goroutines with closing a channel */
package main

import (
	"fmt"
	"time"
)

func main() {
	// Channel which all goroutines wait on
	ch := make(chan bool)
	out := make(chan bool)
	count := 10

	// Spawn some goroutines
	for i := 0; i < count; i++ {
		go func(i int) {
			fmt.Printf("%d waiting\n", i)
			<-ch
			fmt.Printf("%d done waiting\n", i)
			out <- true
		}(i)
	}

	fmt.Println("Nap time")
	time.Sleep(1e9)
	fmt.Println("Wakeup!")

	// Wake up goroutines
	close(ch)

	// Wait for goroutines
	for i := 0; i < count; i++ {
		<-out
	}
}