Middle+
Racontes-moi plus sur WaitGroup: kā tas darbojas, ko dara Add, Done, Wait?
sobes.tech AI
Vastus AI-lt
In Go, WaitGroup is used to wait for a collection of goroutines to finish.
- Add(n int) — increases the counter by n, usually called before starting goroutines.
- Done() — decreases the counter by 1, called inside a goroutine after completing its work.
- Wait() — blocks execution until the counter reaches zero, i.e., until all goroutines have called Done.
Example:
var wg sync.WaitGroup
wg.Add(3) // wait for 3 goroutines
for i := 0; i < 3; i++ {
go func(id int) {
defer wg.Done()
fmt.Println("Goroutine", id, "completed")
}(i)
}
wg.Wait() // wait for all goroutines to finish
fmt.Println("All goroutines have finished")
This way, WaitGroup helps synchronize parallel tasks and wait for their completion.