Middle+
Tell me about WaitGroup in Go.
sobes.tech AI
Answer from AI
In Go, sync.WaitGroup is used to wait for a group of goroutines to finish. It is a convenient way to synchronize parallel tasks.
Main methods:
Add(int)— increases the counter of goroutines to wait for.Done()— decreases the counter, called when a goroutine finishes.Wait()— blocks execution until the counter becomes zero.
Example of usage:
var wg sync.WaitGroup
wg.Add(2) // expecting 2 goroutines
go func() {
defer wg.Done()
// work of the first goroutine
}()
go func() {
defer wg.Done()
// work of the second goroutine
}()
wg.Wait() // wait for both to finish
Thus, WaitGroup helps control the completion of parallel operations.