go runtime_error ai_generated true

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

context canceled: goroutine pool worker detected cancellation after returning result

ID: go/context-canceled-in-goroutine-pool

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://pkg.go.dev/context#Context

解决方案

  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

无效尝试

常见但无效的做法:

  1. 85% 失败

    Without context checks, workers cannot be cancelled mid-task, leading to resource leaks and slow shutdowns.

  2. 70% 失败

    If the parent context is cancelled, derived contexts are also cancelled; doesn't solve the race condition.

  3. 60% 失败

    Mutexes don't prevent the race between context cancellation and result computation; can cause deadlocks.