As asked
Explain how context.WithCancel works internally. If I cancel a parent context, how does the signal propagate to child contexts, and what responsibility do goroutines have when they receive a cancellation?
Sample answer outline
A strong answer explains that WithCancel creates a child cancelCtx and registers it with the parent by walking up the tree to find the nearest cancelCtx ancestor and appending to its children map. When the parent is cancelled it iterates its children and calls their cancel functions. Goroutines are responsible for selecting on ctx.Done() and returning promptly when the channel is closed, releasing resources and avoiding leaks.
Expect these follow-ups
- What is the difference between context.WithTimeout and context.WithDeadline?
- What happens if you forget to call the cancel function returned by WithCancel?