User Tools

Site Tools


go:concurrency:waitgroup

sync.WaitGroup

What is it?

`sync.WaitGroup` is a counter-based synchronization primitive used to wait for a set of goroutines to finish.

What is it used for?

  • Start N goroutines and wait until all of them are done.
  • Coordinate parallel tasks (fan-out) and join results (fan-in).

When to use

  • You want to block until all spawned goroutines complete.
  • You do NOT need cancellation/timeouts (if you do, combine with `context`).

Example

package main
 
import (
    "fmt"
    "sync"
)
 
func main() {
    var wg sync.WaitGroup
 
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            fmt.Println("worker:", id)
        }(i)
    }
 
    wg.Wait()
    fmt.Println("all done")
}

Notes / pitfalls

  • Call `Add(n)` before starting goroutines (common best practice).
  • Each goroutine must call `Done()` exactly once.
  • Do NOT copy a `WaitGroup` after first use.
  • Avoid calling `Add()` concurrently with `Wait()` unless you really know what you’re doing.

Hard words (English)

  • counter /ˈkaʊntər/: bộ đếm
  • coordinate /koʊˈɔːrdɪneɪt/: điều phối
  • fan-out /ˈfæn aʊt/: tỏa ra nhiều nhánh xử lý
  • fan-in /ˈfæn ɪn/: gom nhiều nhánh về một
  • cancellation /ˌkænsəˈleɪʃən/: huỷ
go/concurrency/waitgroup.txt · Last modified: by phong2018