Sobes.tech
Junior — Middle

Kas saaksite selgitada, mis on Wait Group ja milleks seda programmeerimises kasutatakse?

sobes.tech AI

Vastus AI-lt

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 their work.

Main methods:

  • Add(int) — increases the counter of expected goroutines.
  • Done() — decreases the counter, called when a goroutine finishes.
  • Wait() — blocks execution until the counter reaches zero.

Usage example:

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.