go
resource_error
ai_generated
true
error: context deadline exceeded (goroutine blocked on <-ch after cancel)
ID: go/goroutine-leak-on-ctx-cancel
80%Fix Rate
87%Confidence
0Evidence
2024-08-09First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
Select on ctx.Done() alongside the channel: select { case v := <-ch: return v, nil case <-ctx.Done(): return nil, ctx.Err() } -
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:
-
70% fail
Delays the leak; cancel still leaves the receiver blocked.
-
65% fail
default makes the loop spin hot and still does not deliver the value.