Sobes.tech
Junior — Middle

Mis on kontekst gorutinas ja kuidas seda kasutatakse?

sobes.tech AI

Vastus AI-lt

In Go, the context.Context is an object used for passing data between goroutines, such as deadlines, cancellation signals, and request-scoped values. The context helps manage the lifecycle of goroutines and cancel them if necessary.

Main uses of context:

  • Cancel a goroutine's work (e.g., on timeout or request cancellation)
  • Pass a deadline (the time by which the operation should be completed)
  • Pass request-scoped values (e.g., user ID or token)

Example of usage:

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()

select {
case <-time.After(time.Second * 10):
    fmt.Println("operation completed")
case <-ctx.Done():
    fmt.Println("operation canceled or timed out")
}

This way, the context allows controlling the execution of goroutines and passing necessary parameters without using global variables.