liveBook · Manning

Add method

As explained in 100 Go Mistakes and How to Avoid Them

The Add method of sync.WaitGroup changes the number of concurrent operations that a WaitGroup waits to complete.

The Add method changes a sync.WaitGroup counter: positive values register operations, while negative values—typically through Done—finish them. Wait blocks until the counter reaches zero; a negative counter panics. section 9.11

A frequent mistake is calling wg.Add(1) inside the goroutine it is meant to register. The parent may reach wg.Wait before that call, observe a zero counter, and continue while work is still running. section 9.11

Incorrect registration

for i := 0; i < 3; i++ { go func() { wg.Add(1) atomic.AddUint64(&v, 1) wg.Done() }() } wg.Wait() fmt.Println(v) This can print any value from 0 to 3: the parent can return from Wait before the last goroutine increments the counter and updates v. section 9.11

Register work before starting it:

  • Use atomic operations for shared counters, but do not treat atomic updates as a substitute for WaitGroup synchronization. section 9.11

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains counter updates and traces the race caused by calling Add inside a goroutine, then contrasts corrected placements.
Examples
Uses three goroutines updating an atomic counter and compares registration inside versus before goroutine creation.
What it assumes
Assumes goroutines, WaitGroup.Wait, Done, and atomic counter updates.
What you can do after
Operate WaitGroup safely by registering work before launching goroutines and matching each registration with completion.
How it connects
Connects Add with Wait, Done, goroutines, atomic operations, and the race detector.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.