Junior — Middle
What functions does the WaitGroup structure provide in the Go language for goroutine synchronization?
sobes.tech AI
Answer from AI
In the Go language, the sync.WaitGroup structure is used for synchronizing multiple goroutines, allowing the main goroutine to wait for others to complete.
Main methods of WaitGroup:
-
Add(delta int)— increases or decreases the counter of goroutines to wait for. Usually called before starting goroutines. -
Done()— decreases the counter by 1, called at the end of a goroutine. -
Wait()— blocks execution until the counter reaches zero.
Example of 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.Println("Goroutine", id)
}(i)
}
wg.Wait() // wait for all goroutines to finish
fmt.Println("All goroutines are finished")
Thus, WaitGroup helps coordinate parallel execution and ensures that the program does not terminate prematurely.