sync.WaitGroup

A WaitGroup lets a program wait until a group of goroutines has completed. Its Add, Done, and Wait methods maintain a counter representing the work that is still outstanding.

Minimal example

go
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    fmt.Println("finished")
}()
wg.Wait()

Learn this concept

Lesson 1.13 · Goroutines, WaitGroup and the race detector

Used in exercises

Exercise 1.15 · Table-driven tests with a fake clock, plus one race test Exercise 5.13 · Hub broadcast and claim race tests
Prerequisite conceptsGoroutinesGo defer