go resource_error ai_generated true

error: context deadline exceeded (goroutine blocked on <-ch after cancel)

ID: go/goroutine-leak-on-ctx-cancel

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.20 active — — —
1.21 active — — —
1.22 active — — —

Root Cause

A goroutine waits on a channel that is only written on success. When ctx is cancelled the sender returns early and never sends, leaving the receiver blocked forever.

generic

中文

goroutine 等待一个仅在成功时写入的 channel。ctx 取消后发送者提前返回从不发送,接收者永远阻塞。

Workarounds

  1. 95% success
    Select on ctx.Done() alongside the channel:
    
    select {
    case v := <-ch:
        return v, nil
    case <-ctx.Done():
        return nil, ctx.Err()
    }
  2. 90% success
    Ensure producers always send or close on exit:
    
    defer close(ch)
    for _, item := range items {
        select {
        case ch <- item:
        case <-ctx.Done():
            return
        }
    }

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Delays the leak; cancel still leaves the receiver blocked.

  2. 65% fail

    default makes the loop spin hot and still does not deliver the value.