Sobes.tech
Middle — Senior

Какова роль метода Wg.Wait в синхронизации потоков?

sobes.tech AI

Answer from AI

The Wg.Wait() method from the sync package in Go is used for synchronizing multiple goroutines. It blocks the execution of the calling goroutine until the WaitGroup counter becomes zero, meaning all goroutines added via Add() have called Done().

Example:

var wg sync.WaitGroup
wg.Add(2)

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 goroutines to finish

Thus, Wg.Wait() guarantees that the program will not continue until all parallel tasks are completed.