The sync package provides synchronization tools for coordinating goroutines. Its WaitGroup type replaces a channel-based waiting pattern when a program must wait for several goroutines to finish. section 7.2.4
Use a WaitGroup by following this sequence:
- Create a WaitGroup, commonly as wg := &sync.WaitGroup{}. section 7.2.4
- Call Add with the number of goroutines to track before launching them. section 7.2.4
- Pass the pointer to each goroutine and defer Done so the shared WaitGroup is notified even when the function returns. section 7.2.4
- Call Wait after launching the goroutines; it returns after the matching Done calls. section 7.2.4
Listing 7.7 Cooking example using sync.WaitGroup
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{} #1
wg.Add(2) #2
go cookRice(wg) #3
go cookCurry(wg) #3
wg.Wait() #4
}
func cookRice(wg *sync.WaitGroup) {
defer wg.Done() #5
fmt.Println("Cooking rice...")
// prepare rice
}
func cookCurry(wg *sync.WaitGroup) {
defer wg.Done() #5
fmt.Println("Preparing curry sauce...")
// prepare curry
}
A complete cooking example coordinates rice and curry goroutines with Add, deferred Done, and Wait. section 7.2.4


