Select and Cancellation
What you will learn
- coordinate multiple channel operations with
select; - propagate cancellation using contexts;
- avoid leaked timeout and background work;
select waits for one of several channel operations to become ready. It is the control statement that connects concurrent events.
select {
case value := <-results:
fmt.Println("result:", value)
case err := <-failures:
fmt.Println("failed:", err)
}
If several cases are ready, Go chooses one pseudo-randomly. If none is ready, select blocks.
Timeouts
select {
case result := <-results:
fmt.Println(result)
case <-time.After(2 * time.Second):
fmt.Println("timed out")
}
This is convenient for one-off waits. In repeated loops, use and stop a time.Timer instead of repeatedly allocating time.After timers.
Non-blocking operations
A default case runs immediately when no channel case is ready:
select {
case job := <-jobs:
process(job)
default:
fmt.Println("no job available")
}
Use this carefully. A loop containing a default case can spin continuously and waste CPU.
Why cancellation matters
Suppose an HTTP request starts several goroutines. If the client disconnects, those goroutines should stop instead of continuing work nobody needs.
The context package carries cancellation, deadlines, and request-scoped values across API boundaries.
func work(ctx context.Context, items <-chan string) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case item, ok := <-items:
if !ok {
return nil
}
fmt.Println("processing", item)
}
}
}
ctx.Done() is closed when the context is cancelled or reaches its deadline.
Create and cancel a context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
if err := work(ctx); err != nil {
log.Println(err)
}
}()
// Later, when the work is no longer needed:
cancel()
Always call the returned cancel function. It releases resources even if the operation finishes before the deadline.
Context rules
- Accept
context.Contextas the first parameter, usually namedctx. - Do not store a context in a struct for ordinary request work.
- Pass the existing context down instead of replacing it with
context.Background(). - Use context values only for request-scoped metadata, not ordinary optional parameters.
- A function that starts work should document whether cancellation stops that work promptly.
Practice
Create a worker that prints a counter every 100 milliseconds. Stop it through a context after one second, and make main wait for the worker to confirm it has returned.
context.Context as the first parameter, select on both the work operation and ctx.Done(), and return ctx.Err() when cancelled. The caller creates and cancels the context; do not store it in a long-lived struct.Summary
selectwaits on whichever channel case can proceed.- Context propagates deadlines and cancellation across call boundaries.
- Cancellation must be observed by every blocking stage to stop the full pipeline.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.