Junior — Middle
Can you change the number of waiting threads in a synchronizing group in Go during program execution?
sobes.tech AI
Answer from AI
In Go, the number of goroutines waiting in a sync.WaitGroup can be changed during program execution using the methods Add, Done, and Wait.
- The
Add(n int)method increases or decreases the counter of waiting goroutines byn. It can be called multiple times to dynamically change the number of waiters. - The
Done()method is equivalent toAdd(-1)and decreases the counter by 1. - The
Wait()method blocks execution until the counter reaches zero.
Important: you cannot call Add with a negative value if the counter is already zero, otherwise a panic will occur.
Example:
var wg sync.WaitGroup
wg.Add(2) // expecting 2 goroutines
go func() {
defer wg.Done()
// work 1
}()
go func() {
defer wg.Done()
// work 2
}()
// You can add more waits during execution
wg.Add(1)
go func() {
defer wg.Done()
// additional work
}()
wg.Wait() // wait for all to finish
Thus, the number of waiters in WaitGroup can be changed dynamically, as long as Add and Done are used correctly.