go runtime_error ai_generated true

error: WaitGroup misuse: Add called concurrently with Wait

ID: go/waitgroup-add-after-wait

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

wg.Add is invoked from a goroutine while another goroutine is inside wg.Wait, which the sync package explicitly forbids and can race or panic.

generic

中文

一个 goroutine 在调用 wg.Add 时,另一个 goroutine 正在 wg.Wait 中,这是 sync 包明确禁止的,会导致竞态或 panic。

Workarounds

  1. 95% success
    wg.Add(len(tasks))
    for _, t := range tasks {
        go func(t Task) { defer wg.Done(); run(t) }(t)
    }
    wg.Wait()
  2. 92% success
    jobs := make(chan Job)
    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() { defer wg.Done(); for j := range jobs { run(j) } }()
    }
    for _, j := range all { jobs <- j }
    close(jobs)
    wg.Wait()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Deadlocks: Wait holds the lock while waiting for Done, but Done is inside the locked section.

  2. 60% fail

    Over-counting causes Done panics; under-counting returns early.