Why This Happens
sync.WaitGroup.Add must be called before the goroutine starts, not inside it. If Add runs concurrently with Wait, there is a race: Wait might return before Add increments the counter, causing the program to exit before all goroutines finish.
The Problem
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
go func() {
wg.Add(1) // race with wg.Wait()
defer wg.Done()
doWork()
}()
}
wg.Wait()
}The Fix
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
doWork()
}()
}
wg.Wait()
}Step-by-Step Fix
- 1
Identify the misplaced Add
Find wg.Add calls that are inside the goroutine function instead of before the go statement.
- 2
Move Add before go
Place wg.Add(1) immediately before the go statement that launches the goroutine.
- 3
Verify Done matches Add
Ensure every goroutine calls wg.Done() exactly once, usually with defer.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free