Junior — Middle
Какое назначение у конструкции Wait Group в синхронизации горутин?
sobes.tech AI
Answer from AI
WaitGroup in Go is used for synchronizing multiple goroutines. It allows the main goroutine (or any other) to wait for a group of goroutines to finish.
The main purpose of WaitGroup is to track the number of active goroutines and block execution until all of them have completed.
Example usage:
var wg sync.WaitGroup
wg.Add(3) // expecting 3 goroutines to finish
for i := 0; i < 3; i++ {
go func(id int) {
defer wg.Done() // signal goroutine completion
// goroutine work
fmt.Println("Goroutine", id, "completed")
}(i)
}
wg.Wait() // wait until counter reaches 0
fmt.Println("All goroutines are finished")
Thus, WaitGroup helps coordinate parallel execution and ensures that the program does not continue until all necessary goroutines have finished.