Senior
How is context cancellation implemented? What happens inside?
sobes.tech AI
Answer from AI
In Go, the context (context.Context) is used to manage the lifetime of operations, pass cancellation signals, and deadlines.
Context cancellation is implemented by creating a child context with a cancel function, which signals all listeners to stop work when called.
The process involves:
- Creating a channel that is closed upon context cancellation.
- All functions receiving this context can listen to this channel and react to its closure (e.g., interrupt operations).
- Cancellation can be triggered manually (by calling the cancel function) or automatically when a deadline is reached.
Example:
ctx, cancel := context.WithCancel(context.Background())
// Launch a goroutine that listens for cancellation
go func() {
<-ctx.Done() // wait for cancel signal
fmt.Println("Context cancelled")
}()
// At some point, trigger cancellation
cancel()
Thus, context cancellation is a coordination mechanism between goroutines via a channel signaling the need to terminate work.