WaitGroups
Use sync.WaitGroup to wait for a collection of goroutines to finish.
A sync.WaitGroup counts tasks and lets one goroutine wait until the count reaches zero. Add before launching each goroutine, call Done when it finishes, and call Wait to block.
When passing a wait group to another function, pass it by pointer. Defer Done so it runs when the worker returns.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Println("worker", id)
}(i)
}
wg.Wait()
fmt.Println("all done")
}In production
Do not copy a WaitGroup after its first use. Add a positive count before starting a goroutine when the counter may be zero, otherwise Wait can return before the task is registered. Done runs during panic unwinding, but it does not recover the panic.
Enjoyed this? Get more software craft delivered to your inbox.