Sobes.tech
Junior — Middle

Can you explain what a Wait Group is and what it is used for in programming?

sobes.tech AI

Answer from AI

Wait Group in Go is a structure from the sync package used to wait for a group of goroutines to finish. It allows the main goroutine (or another) to block until all started goroutines complete.

Main methods:

  • Add(int) — increases the counter of goroutines to wait for.
  • Done() — decreases the counter, called upon goroutine completion.
  • Wait() — blocks execution until the counter reaches zero.

Example usage:

var wg sync.WaitGroup
wg.Add(2) // waiting for 2 goroutines

go func() {
    defer wg.Done()
    // work of the first goroutine
}()

go func() {
    defer wg.Done()
    // work of the second goroutine
}()

wg.Wait() // wait for both to finish

This is useful for synchronizing parallel tasks and preventing premature program termination.

Can you explain what a Wait Group is and what it is… - sobes.tech