go runtime_error ai_generated true

context canceled: goroutine pool worker detected cancellation after returning result

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
1Evidence
2024-03-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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 — — —

Root Cause

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

中文

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

Official Documentation

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

Workarounds

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

中文步骤

  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

Dead Ends

Common approaches that don't work:

  1. 85% fail

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

  2. 70% fail

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

  3. 60% fail

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