Middle
Mis on kontekst Go-s? Milleks seda kasutatakse? Kuidas töötab ajapiirangu tühistamine?
sobes.tech AI
Vastus AI-lt
In Go, context is a package and a concept for managing the lifetime of operations, transmitting cancel signals, and setting time limits between goroutines.
Main tasks of the context:
- Cancel operations (e.g., on timeout or user cancellation),
- Transmit values (e.g., request ID) through the call chain,
- Set time limits (timeouts).
Timeout-based cancellation works as follows:
- A context with a timeout or deadline is created, for example,
context.WithTimeout. - When the time expires, the context is automatically canceled.
- The goroutine listening to this context receives a cancel signal via the
Done()channel. - The goroutine must handle cancellation properly (e.g., stop work and free resources).
Example:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation canceled or timed out")
}
Here, the operation will be interrupted after 2 seconds if it does not finish earlier.