Go⚡Concurrencyintermediate
sync.WaitGroup
Go · Concurrency · Run with go run
Explanation
`sync.WaitGroup` coordinates a set of goroutines: `Add(n)` registers n tasks, each goroutine calls `Done()` when finished, and `Wait()` blocks until the count reaches zero. It is the standard way to launch a batch of goroutines and wait for all of them to complete before proceeding.
Real-World Scenario
Processing a batch of images in parallel — launch one goroutine per image with `wg.Add(1)` and `go process(img)`, then `wg.Wait()` before writing the results to disk. The main goroutine doesn't proceed until all images are done.
Quick Snippet
snippet.go
import "sync"
func processAll(items []string) {
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(item string) {
defer wg.Done()
process(item)
}(item) // pass item to avoid closure capture (pre-Go1.22)
}
wg.Wait() // blocks until all goroutines call Done
fmt.Println("all done")
}Full Example
waitgroup.go
// Compile: go run waitgroup.go
// Output (order varies):
// processed item-1
// processed item-2
// processed item-3
// all done
package main
import (
"fmt"
"sync"
)
func process(item string) {
fmt.Println("processed", item)
}
func main() {
items := []string{"item-1", "item-2", "item-3"}
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(item string) {
defer wg.Done()
process(item)
}(item)
}
wg.Wait() // blocks until every goroutine calls Done
fmt.Println("all done")
}
Run command
go run waitgroup.go