Middle+
Tell about the context in Go: what is it used for, how does cancellation work?
sobes.tech AI
Answer from AI
The Go package context is used for passing cancellation signals, deadlines, and other values between goroutines, especially in network and long-running operations.
Main points:
-
What it is used for:
- Canceling operations (e.g., HTTP requests, database queries) when time expires or upon signal.
- Passing deadlines (timeouts).
- Passing request-related values (e.g., identifiers, tokens).
-
How cancellation works:
- A context with a cancel function (
context.WithCancel) is created, which returns a new context and a cancel function. - When the cancel function is called, all goroutines listening to this context receive a signal and can terminate their work.
- A context with a cancel function (
Example:
ctx, cancel := context.WithCancel(context.Background())
// Launch a goroutine that listens for cancellation
go func() {
<-ctx.Done()
fmt.Println("Operation canceled")
}()
// Cancel the context after some time
cancel()
Thus, context helps manage the lifecycle of operations and prevent resource leaks.