Propagate context cancellation
Propagate context cancellation
A context carries cancellation, deadlines and request-scoped information through function calls. Pass ctx context.Context as the first parameter. context.Background() supplies a root; context.WithCancel(parent) returns a child and a function that signals cancellation. A context is safe to share among goroutines, but it does not forcibly terminate them.
package main
import ( "context" "fmt")
func main() { parent, cancel := context.WithCancel(context.Background()) defer cancel() child, finish := context.WithCancel(parent) defer finish() cancel() <-child.Done() fmt.Println(child.Err() == context.Canceled)}Done returns a channel that closes on cancellation; Err reports the reason after cancellation. Canceling a parent also cancels derived children. Canceling a child does not cancel its parent. Call every owned cancel function, normally with defer immediately after creation. Use Background for roots and TODO when the correct parent is not yet known, rather than nil.
Expected output:
trueCancel a blocked worker and wait for it
package main
import ( "context" "fmt")
func receive(ctx context.Context, jobs <-chan int) error { select { case <-ctx.Done(): return ctx.Err() case <-jobs: return nil }}func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() jobs := make(chan int) finished := make(chan error, 1) go func() { finished <- receive(ctx, jobs) }() cancel() fmt.Println(<-finished == context.Canceled)}No sender exists, so cancellation is the only possible completion. The worker observes Done and returns; main waits for its result. Calling cancel alone does not join workers or interrupt arbitrary blocking I/O. Use context-aware APIs or an explicit stop mechanism, and keep the parent context when calling downstream functions.
Expected output:
trueTry it locally
Derive two children from one cancellable parent. Cancel the first child and print whether the second remains active. Then cancel the parent and wait for the second Done; print whether its Err is context.Canceled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 05: Propagate context cancellation
Check the lesson objective before moving on.
Which direction does ordinary context cancellation propagate?
What does cancel guarantee about a worker?