go runtime_error ai_generated true

panic: sync: WaitGroup misuse: Add called concurrently with Wait

ID: go/context-cancellation-race

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.22 active

Root Cause

Calling Add() on a WaitGroup concurrently with Wait(), often due to canceling context that triggers new goroutines while waiting.

generic

中文

在 Wait() 并发调用 Add(),通常是因为取消 context 导致在等待时启动了新的 goroutine。

Workarounds

  1. 95% success
    Ensure all Add calls happen before Wait by using a separate goroutine to start workers: 
    
    var wg sync.WaitGroup
    for i := 0; i < n; i++ {
        wg.Add(1)
        go func() { defer wg.Done(); /* work */ }()
    }
    wg.Wait()
  2. 90% success
    Use a channel to signal completion instead of WaitGroup when dynamic goroutine creation is needed.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Doesn't prevent Add from being called after Wait has started.

  2. 60% fail

    If goroutines are started from a context cancellation callback, it may be too late.