Or-done channel
Wrap channel reads so downstream consumers stop promptly when cancellation wins instead of blocking on abandoned input.
Canonical guidance
- stop consuming input when cancellation makes more work irrelevant
- isolate cancellation plumbing in one wrapper instead of scattering repeated
selectlogic - keep wrapper ownership clear
Use when
- channel pipelines
- stream adapters
- cancellation-aware fan-in stages
Avoid
- ranging the input directly when the caller may stop early
- duplicating slightly different cancellation wrappers everywhere
- forgetting to close the wrapper output when it owns that output
Preferred pattern
- a wrapper goroutine relays values until either
donecloses or the input ends
Anti-pattern
- a pipeline stage that assumes the consumer will always drain every value
Explanation: This is tempting because demos often drain fully, but real callers often stop early.
Why
- abandoned reads are a common source of goroutine leaks
Related pages
Sources
- Advanced Go Concurrency Patterns - Sameer Ajmani
- Go Concurrency Patterns: Pipelines and cancellation - Sameer Ajmani
- Go Concurrency Patterns: Context - Sameer Ajmani