Sobes.tech
Junior — Middle

Milline on WaitGroup struktuuri roll ja eesmärk Go arendamisel?

sobes.tech AI

Vastus AI-lt

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

Main methods:

  • Add(int): increases the count of goroutines to wait for.
  • Done(): decreases the count by 1, called when a goroutine finishes.
  • Wait(): blocks execution until the counter reaches 0.

Usage example:

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

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

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

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

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