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
- context — The Go standard library package whose Context value carries a deadline, a cancellation signal and request-scoped values through a chain of function calls.
- context deadline — A time limit attached to a context, after which it is cancelled automatically and ctx.Err() reports context.DeadlineExceeded.
- select statement — A Go statement that waits on several channel operations at once and runs the first one that is ready.
- goroutine leak — A goroutine that never finishes because it is stuck waiting for something that will never happen, slowly wasting memory.
Taught in
- The select Statement — Concurrent Systems Programming with Go
- The context Package — Concurrent Systems Programming with Go
- Context Cancellation and Timeouts — Concurrent Systems Programming with Go
- The time Package — Concurrent Systems Programming with Go
- Calling APIs with net/http Client — Concurrent Systems Programming with Go
- Handling Timeouts and Errors — Concurrent Systems Programming with Go