# fatal error: 所有 goroutine 都在休眠 - 死锁！（WaitGroup.Wait 在 Add 之前返回）

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

## 根因

wg.Add(1) 被放在新 goroutine 内部而不是 go 之前调用，导致 wg.Wait() 可能看到计数器为零而提前返回，或程序死锁。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.0+ | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   for _, item := range items {
    wg.Add(1)
    go func(item Item) {
        defer wg.Done()
        process(item)
    }(item)
}
wg.Wait()
   ```
2. **** (93% 成功率)
   ```
   g, ctx := errgroup.WithContext(context.Background())
for _, item := range items {
    item := item
    g.Go(func() error { return process(ctx, item) })
}
return g.Wait()
   ```

## 无效尝试

- **** — Sleep is a race; under load the goroutine still may not have run Add before Wait. (75% 失败率)
- **** — Doubling the count causes Wait to block forever or triggers a negative counter panic. (80% 失败率)
