# 上下文已取消：goroutine 池工作线程在返回结果后检测到取消

- **ID:** `go/context-canceled-in-goroutine-pool`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

goroutine 池中的工作线程在计算结果后检查上下文取消，当父上下文在工作线程返回前被取消时，导致假阳性取消错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Go 1.15 | active | — | — |
| Go 1.16 | active | — | — |
| Go 1.17 | active | — | — |
| Go 1.18 | active | — | — |
| Go 1.19 | active | — | — |
| Go 1.20 | active | — | — |
| Go 1.21 | active | — | — |
| Go 1.22 | active | — | — |
| Go 1.23 | active | — | — |

## 解决方案

1. ```
   Check context cancellation before computation, not after; use select with both context.Done() and result channel
   ```
2. ```
   Use a sync.WaitGroup or atomic flag to ensure result is fully sent before checking cancellation
   ```
3. ```
   Ignore cancellation error if result was successfully computed and sent; log but don't propagate
   ```

## 无效尝试

- **** — Without context checks, workers cannot be cancelled mid-task, leading to resource leaks and slow shutdowns. (85% 失败率)
- **** — If the parent context is cancelled, derived contexts are also cancelled; doesn't solve the race condition. (70% 失败率)
- **** — Mutexes don't prevent the race between context cancellation and result computation; can cause deadlocks. (60% 失败率)
