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

- **ID:** `go/waitgroup-misuse-add-inside-goroutine`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

wg.Add() 与 wg.Wait() 并发执行，或在所有 Wait 返回前重用了 WaitGroup。这是 Add 与 Wait 之间的竞态。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.18 | active | — | — |
| 1.22 | active | — | — |

## 解决方案

1. **** (92% 成功率)
   ```
   wg.Add(n)
for i := 0; i < n; i++ {
    go worker(&wg)
}
wg.Wait()
   ```
2. **** (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()
}
   ```

## 无效尝试

- **** — Sleep doesn't establish happens-before ordering; the race can still occur and only masks the bug intermittently. (85% 失败率)
- **** — Sharing one WaitGroup across independent operations increases the chance of Add/Wait overlap, worsening the race. (80% 失败率)
