go / intermediate
Snippet
Synchronizing Tasks with sync.WaitGroup
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for, each worker calls Done when finished, and Wait blocks until all are complete.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
func processAll() {var wg sync.WaitGroupfor i := 1; i <= 3; i++ {wg.Add(1)go func(id int) {defer wg.Done()fmt.Printf("Worker %d started\n", id)time.Sleep(time.Second)}(i)}wg.Wait()fmt.Println("All workers finished")}
Breakdown
1
wg.Add(1)
Increments the WaitGroup counter for each new goroutine.
2
defer wg.Done()
Decrements the counter when the goroutine finishes its execution.
3
wg.Wait()
Blocks execution until the WaitGroup counter reaches zero.