Context and Cancellation

A context.Context is a stop button and a deadline that you pass down to everything doing work.

The idea

You order food and tell the kitchen “if it is not ready in 20 minutes, cancel it”. Every cook working on your order can look at the same clock: when it rings, they all stop and clean up instead of finishing something nobody wants.

A context is that shared clock/stop button. context.WithCancel gives you a button; WithTimeout presses it automatically after a time. Contexts form a tree: cancelling a parent cancels every child below it, never the other way round. Work listens with <-ctx.Done().

Watch it work

Try it

Common mistakes