# 恐慌：同步：WaitGroup计数器为负

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

## 根因

对WaitGroup调用Done()的次数超过Add()调用的次数，通常是由于协程生命周期管理不匹配。

## 版本兼容性

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

## 解决方案

1. **Ensure Add() is called exactly once per goroutine before starting it** (98% 成功率)
   ```
   var wg sync.WaitGroup
for i := 0; i < n; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        // work
    }()
}
wg.Wait()
   ```
2. **Use atomic counter with careful increment/decrement** (80% 成功率)
   ```
   var counter int64
atomic.AddInt64(&counter, 1)
go func() {
    // work
    atomic.AddInt64(&counter, -1)
}()
   ```

## 无效尝试

- **Adding recover() to catch the panic** — Recover does not fix the underlying counter mismatch; it only hides the symptom. (90% 失败率)
- **Increasing Add() calls arbitrarily** — This can lead to other goroutines waiting indefinitely if Done() is not called enough times. (85% 失败率)
