context cancellation

Telling every function using a context to stop, by calling the cancel function returned when the context was created.

In more detail

Cancelling closes the Done channel, and ctx.Err() then returns context.Canceled. Cancellation is cooperative: code must watch ctx.Done() and return, or it keeps running. Always call cancel, usually with defer, to release resources even when work finishes normally.

Example

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

Related terms

Taught in

References