sync.WaitGroup
Start with sync.WaitGroup
In this lesson, explore sync.waitgroup through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of sync.waitgroup.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
sync.WaitGroup counts unfinished operations. Call Add before starting a task, Done when that task finishes, and Wait to block until the count reaches zero.
Do not copy a WaitGroup after first use. Ensure new tasks are registered before the corresponding Wait begins when it could reach zero.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
results := make([]int, 3)
for i := range results {
wg.Add(1)
go func(n int) { defer wg.Done(); results[n] = n * 2 }(i)
}
wg.Wait()
fmt.Println(results)
}
Output
[0 2 4]Trace what the program does
Add tracks three workers. Each writes a different slice element then signals Done. Wait returns after all writes, giving [0 2 4].
Avoid common mistakes
- Calling Add inside a goroutine may race with Wait when the count is zero.
- A WaitGroup only waits; it does not make unrelated writes mutually exclusive.
Try it yourself
Use WaitGroup to wait for four independent jobs and print an ordered summary.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced sync.WaitGroup in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.