Sobes.tech
Junior — Middle

Kuidas rakendatakse Meetod Wait ja mis on selle peamine funktsioon programmeerimises?

sobes.tech AI

Vastus AI-lt

In Go, the Wait method is most commonly used with the sync.WaitGroup type. Its main function is to block the execution of the current goroutine until the wait group's counter reaches zero. This allows synchronizing the execution of multiple goroutines and waiting for their completion.

Example of usage:

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

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

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

wg.Wait() // blocks until both goroutines call Done()
// the code continues

Thus, Wait provides a convenient way to wait for the completion of multiple parallel tasks.