sync.WaitGroup
sync.WaitGroup waits until a counter reaches zero. Add raises the counter, Done lowers it, Wait blocks until the count is zero. It is the usual way to join a set of goroutines.
Detailed Explanation
You start N workers and you need to know when they have all finished. A WaitGroup is that barrier. wg.Add(n) before the loop (or Add(1) per goroutine before go), defer wg.Done() inside each goroutine, wg.Wait() in the parent.
Add must happen before Wait sees a zero you did not intend. The safe pattern is Add in the goroutine that will Wait, before go. go func() { wg.Add(1); defer wg.Done(); ... }() races: Wait can run before Add. That is a common bug.
Negative count panics. Extra Done or a forgotten Add panics at runtime. Pair them. Add(-1) is allowed and is Done; prefer Done for clarity.
Reuse. After Wait returns, you may Add again and start a new batch. Do not Add from a goroutine that Wait is already waiting on without a clear new cycle; the docs require that the counter not go negative and that Add of a positive delta happen before Wait when the count is zero.
No error value. WaitGroup does not collect errors. Store errors behind a mutex, send them on a channel, or use errgroup.Group, which combines wait and first-error cancel.
What it costs. A WaitGroup is a small struct. A zero value is ready; do not copy it after first use. Copying (passing by value to a function that Adds) is a subtle bug — pass *sync.WaitGroup.
Code Examples
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fmt.Println(i)
}(i)
}
wg.Wait()
}func wrong() {
var wg sync.WaitGroup
go func() {
wg.Add(1) // race with Wait
defer wg.Done()
}()
wg.Wait()
}Common Gotchas
`Add` inside the child races `Wait`
add in the parent before `go`.
Copying a `WaitGroup` after use splits the counter
pass a pointer.
`WaitGroup` ignores errors
use `errgroup` when any worker failure should stop the rest.
A zero `WaitGroup` is ready
no constructor.