go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (WaitGroup.Wait returned before Add)

ID: go/waitgroup-add-inside-goroutine

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-01-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

wg.Add(1) is called inside the spawned goroutine instead of before go, so wg.Wait() can observe a zero counter and return, or the program deadlocks.

generic

中文

wg.Add(1) 被放在新 goroutine 内部而不是 go 之前调用,导致 wg.Wait() 可能看到计数器为零而提前返回,或程序死锁。

Workarounds

  1. 95% success
    for _, item := range items {
        wg.Add(1)
        go func(item Item) {
            defer wg.Done()
            process(item)
        }(item)
    }
    wg.Wait()
  2. 93% success
    g, ctx := errgroup.WithContext(context.Background())
    for _, item := range items {
        item := item
        g.Go(func() error { return process(ctx, item) })
    }
    return g.Wait()

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Sleep is a race; under load the goroutine still may not have run Add before Wait.

  2. 80% fail

    Doubling the count causes Wait to block forever or triggers a negative counter panic.