Is it possible to call WaitGroup.Add inside a goroutine, and Done at the end? Will this work correctly?
sobes.tech AI
Answer from AI
Calling WaitGroup.Add inside a goroutine is possible but requires caution. The main rule is that the number of calls to Add should be known and completed before calling Wait.
If you call Add inside a goroutine that has not yet started or begun work, and Wait has already been called in the main thread, there is a risk that Wait will start waiting before the counter has been increased, and will finish prematurely — leading to synchronization errors.
Correct approach:
- Call
Addbefore starting goroutines to ensure the counter is set. - Inside goroutines, only call
Done.
Example of correct usage:
var wg sync.WaitGroup
wg.Add(3) // pre-increment the counter
for i := 0; i < 3; i++ {
go func() {
defer wg.Done()
// goroutine work
}()
}
wg.Wait()
If Add is called inside a goroutine, Wait may be called before the counter is increased, which can lead to panic or incorrect waiting.
In summary: it is not recommended to call Add inside a goroutine if Wait might already be called.