Channel Synchronization
Use channels as done signals to wait for goroutines to finish before continuing.
A channel can signal that an event has happened. Closing a chan struct broadcasts the signal to every goroutine waiting to receive from it.
Each worker waits on the same channel. Closing it releases every worker, and the wait group lets main wait for them to finish.
package main
import (
"fmt"
"sync"
)
func main() {
done := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
<-done
fmt.Println("worker stopped:", id)
}(i)
}
close(done)
wg.Wait()
}In production
A closed done channel is useful for broadcasting a simple stop signal. For application work that needs cancellation or a deadline across function calls, prefer context.Context, which is supported by many standard library APIs.
Enjoyed this? Get more software craft delivered to your inbox.