Senior
Why do we need WaitGroup in this task?
sobes.tech AI
Answer from AI
WaitGroup in Go is used for goroutine synchronization. In tasks where multiple goroutines are launched, WaitGroup allows the main thread to wait for all started goroutines to finish before proceeding. This prevents premature program exit or moving to the next step when background operations are still ongoing.
Example of usage:
var wg sync.WaitGroup
wg.Add(3) // expecting 3 goroutines
for i := 0; i < 3; i++ {
go func(id int) {
defer wg.Done() // signal completion
// goroutine work
fmt.Println("Goroutine", id, "completed")
}(i)
}
wg.Wait() // wait for all goroutines to finish
fmt.Println("All goroutines are completed")
Thus, WaitGroup ensures proper coordination and prevents race conditions or premature program termination.