go runtime_error ai_generated true

panic: sync: WaitGroup 在上一次 Wait 返回前被重用

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-07-08首次发现

版本兼容性

版本状态引入弃用备注
1.0+ active — — —

根因分析

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

English

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

解决方案

  1. 94% 成功率
    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()
    }

无效尝试

常见但无效的做法:

  1. 85% 失败

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