Sobes.tech
Middle+

Tell me more about WaitGroup: how does it work, what do Add, Done, Wait do?

sobes.tech AI

Answer from AI

WaitGroup in Go is used to wait for a group of goroutines to finish.

  • Add(n int) — increases the counter by n, usually called before starting goroutines.
  • Done() — decreases the counter by 1, called within a goroutine after it completes.
  • Wait() — blocks execution until the counter becomes zero, meaning all goroutines have called Done.

Example:

var wg sync.WaitGroup
wg.Add(3) // wait for 3 goroutines

for i := 0; i < 3; i++ {
    go func(id int) {
        defer wg.Done()
        fmt.Println("Goroutine", id, "completed")
    }(i)
}

wg.Wait() // wait for all goroutines to finish
fmt.Println("All goroutines completed")

Thus, WaitGroup helps synchronize parallel tasks and wait for their completion.