Junior — Middle
What are the consequences if the number of calls to wg.Add does not match the number of goroutines launched?
sobes.tech AI
Answer from AI
In Go, sync.WaitGroup is used to wait for a collection of goroutines to finish. The method wg.Add(n) increments the counter by n, and wg.Done() decrements it by 1. If the number of calls to wg.Add does not match the number of goroutines started (i.e., calls to wg.Done), then:
- If
wg.Addis less than the number ofwg.Donecalls, the counter may become negative whenwg.Doneis called, leading to a runtime panic. - If
wg.Addis greater than the number ofwg.Donecalls, the call towg.Wait()will block forever, as the counter will never reach zero — leading to a deadlock.
Therefore, it is important to call wg.Add with the correct number before starting goroutines and to call wg.Done exactly as many times as wg.Add was called.