# panic: sync: WaitGroup 误用: Add 与 Wait 并发调用

- **ID:** `go/context-cancellation-race`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在 Wait() 并发调用 Add()，通常是因为取消 context 导致在等待时启动了新的 goroutine。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Ensure all Add calls happen before Wait by using a separate goroutine to start workers: 

var wg sync.WaitGroup
for i := 0; i < n; i++ {
    wg.Add(1)
    go func() { defer wg.Done(); /* work */ }()
}
wg.Wait()
   ```
2. **** (90% 成功率)
   ```
   Use a channel to signal completion instead of WaitGroup when dynamic goroutine creation is needed.
   ```

## 无效尝试

- **** — Doesn't prevent Add from being called after Wait has started. (80% 失败率)
- **** — If goroutines are started from a context cancellation callback, it may be too late. (60% 失败率)
