Junior — Middle
Have you used the synchronization mechanism with sync.WaitGroup in your projects?
sobes.tech AI
Answer from AI
Yes, in Go projects, sync.WaitGroup is often used for goroutine synchronization. This mechanism allows waiting for a group of parallel tasks to complete before proceeding.
Working principle:
- An object
WaitGroupis created. - Before starting each goroutine,
Add(1)is called to increment the counter. - Inside the goroutine, after completing its work,
Done()is called to decrement the counter. - The main goroutine calls
Wait(), which blocks until the counter reaches zero.
Example:
var wg sync.WaitGroup
wg.Add(2) // expecting 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 convenient for coordinating parallel operations and preventing premature program termination.