go / intermediate
Snippet
Coordinating Multiple Goroutines with sync.WaitGroup
The sync.WaitGroup is used to coordinate execution flow when starting multiple concurrent tasks in separate goroutines. By calling Add(1) before starting a goroutine and Done() when it exits, we manage a counter of active routines. Wait() blocks execution until this counter drops to zero, guaranteeing that subsequent code runs only after all tasks have finished.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package mainimport ("fmt""sync""time")func performTask(taskID int, wg *sync.WaitGroup) {defer wg.Done()fmt.Printf("Starting task %d\n", taskID)time.Sleep(100 * time.Millisecond)fmt.Printf("Finished task %d\n", taskID)}func coordinateTasks() {var wg sync.WaitGroupfor i := 1; i <= 3; i++ {wg.Add(1)go performTask(i, &wg)}wg.Wait()fmt.Println("All concurrent tasks completed successfully.")}
Breakdown
1
var wg sync.WaitGroup
Declares a Group variable that holds the internal counter of goroutines to wait for.
2
wg.Add(1)
Increments the WaitGroup counter. This must be executed in the main goroutine before starting the sub-goroutine.
3
defer wg.Done()
Ensures the counter is decremented when the goroutine finishes, even if it exits early.
4
wg.Wait()
Blocks the current execution block until the internal WaitGroup counter reaches zero.