0PricingLogin
Go Academy · Lesson

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()

All lessons in this course

  1. sync.Mutex and sync.RWMutex
  2. sync.WaitGroup
  3. sync.Once and sync.Map
  4. Race Detector and Safe Patterns
← Back to Go Academy