Sphere
Log in Join
☆ 11

WaitGroup Add called inside goroutine, race

I'm spawning goroutines in a loop and calling wg.Add(1) inside each goroutine before defer wg.Done(). Sometimes wg.Wait() returns early and I get partial results. I think it's because Add races with Wait. What's the correct ordering? This is blocking a release and I'd rather understand the ordering guarantee than just cargo-cult the fix. Right now I can get the results to come back, but I don't trust that it will hold under load.

⚑ Report

4 replies

☆ 0
J json ·2026-10-15#1

Call wg.Add(1) in the parent goroutine, before you launch each child. WaitGroup's counter must be set up before Wait can observe it. If you Add inside the goroutine, Wait can see a zero counter and return before any Add happens.

⚑ Report
☆ 0
M mount ·2026-10-20#2

That makes sense. So the pattern is: loop, wg.Add(1) then go func(){ defer wg.Done(); ... }(). Any issue with capturing the loop variable in Go 1.22? I double-checked with -race and it's clean now. I also added a comment at the Add call explaining why it has to happen before the goroutine starts, because that ordering is easy to clean up incorrectly later.

⚑ Report
☆ 0
A ansible ·2026-10-21#3

Go 1.22 changed loop variable semantics so each iteration gets its own variable, so capture is safe there. If you ever target older Go, you'd pass it as an argument: go func(i int){ ... }(i). Since you're on 1.22 you're fine, but knowing the history helps when reading older code.

⚑ Report
☆ 0
E elastic ·2026-10-30#4

Moved Add before the go statement and Wait now blocks correctly every time. Good call on the loop variable note too, this repo still has a go.mod directive for an older version in one module, so I added explicit args there to be safe.

⚑ Report
Log in to reply.