Cancel pipelines and propagate errors
Cancel pipelines and propagate errors
A pipeline passes values through stages. If a stage stops early, upstream sends may block forever. Give stages a shared cancellation context and let each stage close only its own output. Here a negative input cancels the pipeline with a cause (Go 1.20+).
package main
import ( "context" "errors" "fmt")
func produce(ctx context.Context, values []int) <-chan int { out := make(chan int) go func() { defer close(out) for _, n := range values { select { case out <- n: case <-ctx.Done(): return } } }() return out}func transform(ctx context.Context, cancel context.CancelCauseFunc, in <-chan int) <-chan int { out := make(chan int) go func() { defer close(out) for { select { case <-ctx.Done(): return case n, ok := <-in: if !ok { return } if n < 0 { cancel(errors.New("negative input")) return } select { case out <- n * 2: case <-ctx.Done(): return } } } }() return out}func main() { ctx, cancel := context.WithCancelCause(context.Background()) defer cancel(nil) in := produce(ctx, []int{2, -1, 9}) for n := range transform(ctx, cancel, in) { fmt.Println(n) } for range in { } fmt.Println(context.Cause(ctx))}The transform receives and forwards 2 before it reads -1. On failure it cancels before closing its output. The producer selects cancellation even if nobody receives; main drains its output after transform has finished, ensuring its output closes. Cancellation is cooperative; if a send and cancellation are both ready, either may win. A caller must decide whether partial results are useful or must be discarded.
Expected output:
4negative inputStop after the first value
package main
import ( "context" "errors" "fmt")
func produce(ctx context.Context, values []int) <-chan int { out := make(chan int) go func() { defer close(out) for _, n := range values { select { case out <- n: case <-ctx.Done(): return } } }() return out}func transform(ctx context.Context, cancel context.CancelCauseFunc, in <-chan int) <-chan int { out := make(chan int) go func() { defer close(out) for { select { case <-ctx.Done(): return case n, ok := <-in: if !ok { return } if n < 0 { cancel(errors.New("negative input")) return } select { case out <- n * 2: case <-ctx.Done(): return } } } }() return out}func main() { ctx, cancel := context.WithCancelCause(context.Background()) in := produce(ctx, []int{1, 2, 3}) out := transform(ctx, cancel, in) fmt.Println(<-out) cancel(errors.New("enough")) for range out { } for range in { } fmt.Println(context.Cause(ctx))}Drain remaining output and wait for closure, rather than assuming cancel instantly terminates goroutines. This toy stage does no blocking work other than channel operations. Real I/O must support cancellation or bounded timeouts too.
Expected output:
2enoughTry it locally
Process [3, 4] with the pipeline; print 6, 8 and whether the cause is nil before deferred cancellation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 03: Cancel pipelines and propagate errors
Check the lesson objective before moving on.
Why select on Done during sends?
What does cancellation guarantee?