Sobes.tech
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:

  1. A context with a timeout or deadline is created, for example, context.WithTimeout.
  2. When the time expires, the context is automatically canceled.
  3. The goroutine listening to this context receives a cancel signal via the Done() channel.
  4. 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.