go runtime_error ai_generated true

error: context canceled (goroutine blocked on channel send after cancellation)

ID: go/context-canceled-while-sending

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-10-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.7+ active

Root Cause

A goroutine keeps sending to a channel after its context is canceled, and the receiver has stopped draining, causing a block or lost work.

generic

中文

goroutine 在 context 被取消后仍向 channel 发送数据,而接收方已停止消费,导致阻塞或工作丢失。

Workarounds

  1. 94% success
    select {
    case ch <- v:
    case <-ctx.Done():
        return ctx.Err()
    }
  2. 90% success
    g, ctx := errgroup.WithContext(ctx)
    g.Go(func() error { return producer(ctx, ch) })
    return g.Wait()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Continues to block on a full channel and wastes resources; the cancellation is not honored.

  2. 75% fail

    Closing while senders are active panics with send on closed channel.