Junior — Middle
Kas kasutas sync.WaitGroup-mehhanismi oma projektides?
sobes.tech AI
Vastus AI-lt
Yes, in Go projects, sync.WaitGroup is often used to synchronize goroutines. This mechanism allows waiting for a group of parallel tasks to complete before continuing.
Working principle:
- An object
WaitGroupis created. - Before starting each goroutine,
Add(1)is called to increase the counter. - Inside the goroutine, after completing the work,
Done()is called, decreasing the counter. - The main goroutine calls
Wait(), which blocks until the counter reaches zero.
Example:
var wg sync.WaitGroup
wg.Add(2) // waiting for 2 goroutines
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 to finish
This is useful for coordinating parallel operations and preventing premature termination of the program.