go
runtime_error
ai_generated
true
panic:sync:WaitGroup 在上一次 Wait 返回前被重用
panic: sync: WaitGroup is reused before previous Wait has returned
ID: go/waitgroup-misuse-add-inside-goroutine
80%修复率
88%置信度
0证据数
2024-06-09首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
wg.Add() 与 wg.Wait() 并发执行,或在所有 Wait 返回前重用了 WaitGroup。这是 Add 与 Wait 之间的竞态。
English
wg.Add() was called concurrently with wg.Wait(), or the WaitGroup was reused before all Wait calls returned. This is a race between Add and Wait.
解决方案
-
92% 成功率
wg.Add(n) for i := 0; i < n; i++ { go worker(&wg) } wg.Wait() -
90% 成功率
for _, batch := range batches { var wg sync.WaitGroup wg.Add(len(batch)) for _, item := range batch { go func(it Item) { defer wg.Done(); process(it) }(item) } wg.Wait() }
无效尝试
常见但无效的做法:
-
85% 失败
Sleep doesn't establish happens-before ordering; the race can still occur and only masks the bug intermittently.
-
80% 失败
Sharing one WaitGroup across independent operations increases the chance of Add/Wait overlap, worsening the race.