sync.WaitGroup
Waiting for a collection of goroutines
Purpose
sync.WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the count, each goroutine calls Done when complete, and Wait blocks until the count reaches zero.
Basic usage
Add before launching each goroutine; Done at the end of each goroutine (via defer); Wait after launching all goroutines.
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(v Item) {
defer wg.Done()
process(v)
}(item)
}
wg.Wait()