go runtime_error ai_generated true

panic: sync: WaitGroup is reused before previous Wait has returned

ID: go/waitgroup-misuse-reused-before-wait

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active — — —

Root Cause

A WaitGroup is reused (Add called) while a previous Wait from another goroutine has not yet returned, violating the rule that Add must happen before Wait.

generic

中文

在上一次 Wait 尚未返回时(另一 goroutine)就再次 Add,违反了 Add 必须先于 Wait 的规则。

Workarounds

  1. 94% success
    Use a fresh WaitGroup per batch instead of reusing one:
    for _, batch := range batches {
        var wg sync.WaitGroup
        for _, x := range batch { wg.Add(1); go func(x T){ defer wg.Done(); work(x) }(x) }
        wg.Wait()
    }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Timing-based synchronization is nondeterministic and the panic can still occur under load.