Sobes.tech
Middle+

Räägi mulle WaitGroup-ist Go-s.

sobes.tech AI

Vastus AI-lt

In Go, sync.WaitGroup is used to wait for a group of goroutines to finish. It is a convenient way to synchronize parallel tasks.

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.

Example of 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 complete

Thus, WaitGroup helps control the completion of parallel operations.