WaitGroups
Context
Section titled “Context”sync.WaitGroup waits for a collection of goroutines to finish. Use Add to set the count, Done to decrement, and Wait to block until the count reaches zero.
Example
Section titled “Example”Start three goroutines and wait for all to complete.
Code example
Section titled “Code example”package main
import ( "fmt" "sync" "time")
func worker(id int, wg *sync.WaitGroup) { defer wg.Done() fmt.Printf("Worker %d starting\n", id) time.Sleep(time.Second) fmt.Printf("Worker %d done\n", id)}
func main() { var wg sync.WaitGroup for i := 1; i <= 3; i++ { wg.Add(1) go worker(i, &wg) } wg.Wait() fmt.Println("All workers finished")}Output
Section titled “Output”Worker 3 startingWorker 1 startingWorker 2 startingWorker 2 doneWorker 1 doneWorker 3 doneAll workers finished