Blocking with Channels in Go
Example 1 In the below code, <-messages will block until it gets something on the channel. This prevents main() from exiting until one item is received on the channel. package main import ( "fmt" "time" ) func waitThenSend(msg chan string) { time.Sleep(2 * time.Second) msg <- "badwolf" } func main() { messages := make(chan string) // make unbuffered channel go func() { waitThenSend(messages) // make goroutine, pass in channel }() <-messages // blocks until channel receives a value fmt.Println("done") } Example 2 The below example demonstrates using a sync.WaitGroupto keep the program running until all of the goroutines have exited. Data is sent to the function via the unbuffered channel named numbers. ...