go
runtime_error
ai_generated
true
上下文已取消:goroutine 池工作线程在返回结果后检测到取消
context canceled: goroutine pool worker detected cancellation after returning result
ID: go/context-canceled-in-goroutine-pool
80%修复率
85%置信度
1证据数
2024-03-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 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 | — | — | — |
根因分析
goroutine 池中的工作线程在计算结果后检查上下文取消,当父上下文在工作线程返回前被取消时,导致假阳性取消错误。
English
A goroutine in a pool checks context cancellation after computing a result, causing a false positive cancellation error when the parent context is cancelled just before the worker returns.
官方文档
https://pkg.go.dev/context#Context解决方案
-
Check context cancellation before computation, not after; use select with both context.Done() and result channel
-
Use a sync.WaitGroup or atomic flag to ensure result is fully sent before checking cancellation
-
Ignore cancellation error if result was successfully computed and sent; log but don't propagate
无效尝试
常见但无效的做法:
-
85% 失败
Without context checks, workers cannot be cancelled mid-task, leading to resource leaks and slow shutdowns.
-
70% 失败
If the parent context is cancelled, derived contexts are also cancelled; doesn't solve the race condition.
-
60% 失败
Mutexes don't prevent the race between context cancellation and result computation; can cause deadlocks.