# fatal error: 所有 goroutine 都处于休眠状态 - 死锁！（wg.Wait 在 goroutine 启动前返回）

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

## 根因

wg.Add(1) 在 goroutine 内部调用而不是之前，导致 Wait() 可能提前返回或永久阻塞，取决于时序。

## 版本兼容性

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

## 解决方案

1. **** (98% 成功率)
   ```
   wg.Add(1)
go func() {
    defer wg.Done()
    work()
}()
wg.Wait()
   ```
2. **** (90% 成功率)
   ```
   done := make(chan struct{}, n)
for i := 0; i < n; i++ {
    go func() { work(); done <- struct{}{} }()
}
for i := 0; i < n; i++ { <-done }
   ```

## 无效尝试

- **** — Sleeping only hides the race; under load the goroutine may still not have run Add in time. (80% 失败率)
- **** — Serialization does not guarantee the goroutine has executed Add before Wait checks the counter. (75% 失败率)
