go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (wg.Wait returns before goroutines start)

ID: go/waitgroup-add-inside-goroutine-race

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —

Root Cause

wg.Add(1) is called inside the goroutine rather than before it, so Wait() can return early or block forever depending on timing.

generic

中文

wg.Add(1) 在 goroutine 内部调用而不是之前,导致 Wait() 可能提前返回或永久阻塞,取决于时序。

Workarounds

  1. 98% success
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
    wg.Wait()
  2. 90% success
    done := make(chan struct{}, n)
    for i := 0; i < n; i++ {
        go func() { work(); done <- struct{}{} }()
    }
    for i := 0; i < n; i++ { <-done }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Sleeping only hides the race; under load the goroutine may still not have run Add in time.

  2. 75% fail

    Serialization does not guarantee the goroutine has executed Add before Wait checks the counter.