Sobes.tech
Junior — Middle

Какова роль и назначение структуры WaitGroup при разработке на Go?

sobes.tech AI

Answer from AI

In Go, the WaitGroup structure is used for synchronizing multiple goroutines. It allows the main goroutine to wait for the completion of a group of other goroutines.

Main methods:

  • Add(int): increases the counter of expected goroutines.
  • Done(): decreases the counter by 1, called upon goroutine completion.
  • Wait(): blocks execution until the counter reaches 0.

Example of usage:

var wg sync.WaitGroup
wg.Add(2) // expecting 2 goroutines

go func() {
    defer wg.Done()
    // goroutine 1 work
}()

go func() {
    defer wg.Done()
    // goroutine 2 work
}()

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

Thus, WaitGroup helps to correctly manage parallel execution and wait for task completion.

Какова роль и назначение структуры WaitGroup при… - sobes.tech