Junior — Middle
Milliseid funktsioone pakub WaitGroup struktuur Go keeles goroutine'ide sünkroniseerimiseks?
sobes.tech AI
Vastus AI-lt
In the Go language, the sync.WaitGroup structure is used to synchronize multiple goroutines, allowing the main goroutine to wait for others to complete.
Main methods of WaitGroup:
-
Add(delta int)— increases or decreases the counter of expected goroutines. Usually called before starting goroutines. -
Done()— decreases the counter by 1, called at the end of a goroutine's work. -
Wait()— blocks execution until the counter reaches zero.
Example of usage:
var wg sync.WaitGroup
wg.Add(3) // waiting for 3 goroutines
for i := 0; i < 3; i++ {
go func(id int) {
defer wg.Done() // signal completion
fmt.Println("Goroutine", id)
}(i)
}
wg.Wait() // wait for all goroutines to finish
fmt.Println("All goroutines completed")
Thus, WaitGroup helps coordinate parallel execution and ensures that the program does not terminate prematurely.