go / expert
Snippet
Advanced Concurrency with Context Cancellation
Context propagation is the idiomatic way to handle timeouts and cancellations across API boundaries and goroutines, preventing resource leaks in complex async workflows.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
func worker(ctx context.Context, results chan<- int) {for {select {case <-ctx.Done():returndefault:// Perform heavy computationresults <- 42}}}
Breakdown
1
case <-ctx.Done():
Triggered when the parent context is cancelled or times out.
2
select { ... }
Allows non-blocking checks of the cancellation state while performing work.