Junior — Middle
Can you explain how the wait mechanism for completing multiple goroutines works in Go using WaitGroup?
sobes.tech AI
Answer from AI
In Go, the sync.WaitGroup type is used to wait for the completion of multiple goroutines. It allows you to "subscribe" to several goroutines and block execution until all of them finish.
Main methods of WaitGroup:
- Add(n int) — increases the counter by n, usually called before starting goroutines.
- Done() — decreases the counter by 1, called at the end of each goroutine.
- Wait() — blocks execution until the counter becomes 0.
Example usage:
var wg sync.WaitGroup
wg.Add(3) // waiting for 3 goroutines
for i := 0; i < 3; i++ {
go func(id int) {
defer wg.Done() // signal completion
fmt.Printf("Goroutine %d is running\n", id)
// some work
}(i)
}
wg.Wait() // wait for all goroutines to finish
fmt.Println("All goroutines are finished")