Senior
Tell me more about WaitGroup: what is it used for, and what methods does it have?
sobes.tech AI
Answer from AI
WaitGroup in Go is used to wait for a group of goroutines to finish. It provides a convenient way to synchronize parallel tasks.
Main methods:
Add(int): increases or decreases the counter of goroutines to wait for.Done(): decreases the counter by 1, called when a goroutine finishes.Wait(): blocks execution until the counter reaches 0.
Example usage:
var wg sync.WaitGroup
wg.Add(2) // expecting 2 goroutines
go func() {
defer wg.Done()
// work 1
}()
go func() {
defer wg.Done()
// work 2
}()
wg.Wait() // wait for both to finish
This allows the main goroutine to wait for all launched parallel tasks to complete.