Coordinate completion with WaitGroup
Coordinate completion with WaitGroup
A WaitGroup counts outstanding work. Register tasks with Add before launching them, defer Done in each task, and call Wait before consuming results. Done subtracts one. Wait returns when the counter reaches zero; it neither returns errors nor cancels tasks.
package main
import ( "fmt" "sync")
func main() { var wg sync.WaitGroup out := make([]int, 4) for i := range out { wg.Add(1) go func(i int) { defer wg.Done(); out[i] = i * i }(i) } wg.Wait() fmt.Println(out)}Passing i explicitly gives each worker its own index, even on older Go loop semantics. Each writes a different slice element; do not append to the same slice concurrently. Done synchronizes before the Wait return it unblocks. Add inside a newly started worker can let Wait return too early. An excessive Done panics when the count becomes negative.
Expected output:
[0 1 4 9]Reuse only after completion
package main
import ( "fmt" "sync")
func main() { var wg sync.WaitGroup for round := 1; round <= 2; round++ { wg.Add(1) go func() { defer wg.Done() }() wg.Wait() fmt.Println("completed", round) }}For independent rounds, start new Add calls only after all previous Wait calls have returned. Positive Add calls when the count is zero must happen before Wait. This chapter uses Go 1.23.2 Add/Done/Wait; newer helper APIs are outside the locally verified scope. A WaitGroup must not be copied after first use.
Expected output:
completed 1completed 2Try it locally
Compute doubled values for [2,4,6] in separate workers and print [4 8 12] after Wait.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 03: Coordinate completion with WaitGroup
Check the lesson objective before moving on.
Where should the initial Add occur?
When may an independent round reuse a WaitGroup?