Go sync.WaitGroup
A WaitGroup tracks outstanding tasks. Add the task count before launching workers and call Done when each worker finishes.
A simple example
sync.WaitGroup
- Start with Two workers each finish once
- Do this Wait for both completions
- Result Wait returns after the second
Syntax
group.Add(n) / group.Done() / group.Wait()
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Wait for independent calculations before reading results
Independent jobs calculate separate parts of a report and can finish out of order. Combine their results only when every required calculation has completed so no contribution is missing.
package main
import (
"fmt"
"sync"
)
func main() {
inputs := []int{2, 3, 4}
results := make([]int, len(inputs))
var group sync.WaitGroup
group.Add(len(inputs))
for i := range inputs {
go func(index int) {
defer group.Done()
results[index] = inputs[index] * inputs[index]
}(i)
}
group.Wait()
fmt.Println(results)
}
[4 9 16]
Each goroutine writes a different slice element. Passing the index as an argument also works on Go versions with shared range variables. Reading after Wait produces deterministic output.
Go documentation for sync.WaitGroup
Combine two gallery entrances
Separate workers count admissions from the north and south doors. Wait until both workers have completed before summing their counts. What total can the coordinator publish?
Combine shift checkouts
Two desks count processed books independently before closing. Wait until both workers have completed before summing their counts. What total can the coordinator publish?