Context Cancellation
Start with Context Cancellation
In this lesson, explore context cancellation through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of context cancellation.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
context.WithCancel creates a child context plus a cancellation function. Call the function when the work is no longer needed; goroutines should watch Done() or call cancellation-aware APIs.
Cancellation is cooperative: it signals the worker but does not forcibly terminate it. Deferred cleanup and explicit shutdown rules remain important.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"context"
"fmt"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
<-ctx.Done()
fmt.Println("Canceled:", ctx.Err() == context.Canceled)
}
Output
Canceled: trueTrace what the program does
Calling cancel closes the Done channel and sets the context error to context.Canceled. The receive returns immediately.
Avoid common mistakes
- Forgeting cancel can retain resources until other cleanup occurs.
- A task must observe cancellation for it to have practical effect.
Try it yourself
Write a worker that selects between a work channel and ctx.Done, then trigger cancel.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Context Cancellation in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.