# panic: sync: WaitGroup 计数器为负数

- **ID:** `go/sync-waitgroup-negative-counter`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

wg.Done() 调用次数大于 wg.Add(n),常见于在未 Add 的 goroutine 中调用 Done,或 Wait 返回后才调用 Add。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.x | active | — | — |

## 解决方案

1. **** (97% 成功率)
   ```
   for _, item := range items {
    wg.Add(1)
    go func(it Item) {
        defer wg.Done()
        process(it)
    }(item)
}
wg.Wait()
   ```
2. **** (95% 成功率)
   ```
   g, ctx := errgroup.WithContext(ctx)
for _, it := range items {
    it := it
    g.Go(func() error { return process(ctx, it) })
}
if err := g.Wait(); err != nil { return err }
   ```

## 无效尝试

- **** — Race with wg.Wait(): Wait may return before Add runs, then Done panics or Wait returns early. (70% 失败率)
- **** — Hides the bug; the WaitGroup is now inconsistent and Wait may hang or return prematurely. (75% 失败率)
