A synchronization point is where concurrent work coordinates or signals completion. In Go, it lets the main function wait until launched goroutines finish before continuing. section 7.2.4
Use a sync.WaitGroup when several goroutines must complete:
- Create a WaitGroup, typically as wg := &sync.WaitGroup{}. section 7.2.4
- Call Add with the number of goroutines being tracked; repeated Add calls also support loop-based launches. section 7.2.4
- Pass the WaitGroup by pointer and defer Done in every goroutine, so the original group receives completion notifications. section 7.2.4
- Call Wait after launching the goroutines; it returns after Done has balanced the registered Add count. section 7.2.4
Waiting for two tasks
A cooking program launches cookRice and cookCurry, registers both with wg.Add(2), and blocks at wg.Wait(). Each function defers wg.Done(), allowing main to continue only after both tasks finish. section 7.2.4
Channels provide another completion signal. A goroutine can send on a channel when its task ends, and the caller can receive once for each expected goroutine. The sending function should close the channel when it owns the channel's completion signal. section 7.2.3
When completion must also carry errors, an error channel can accompany a WaitGroup. errgroup.Group combines goroutine execution with error collection and offers a single Wait call.
