Concurrency

Context

Carries deadlines, cancellation signals, and request-scoped values.

Request cancellationTimeoutsRequest tracing

Understanding Context

Go's context package provides a way to carry deadlines, cancellation signals, and request-scoped values across API boundaries and goroutines. It's essential for graceful shutdown and timeout handling.

How It Works

Parent Context
WithCancel()
Worker 1
ctx.Done()?
Worker 2
ctx.Done()?
Worker 3
ctx.Done()?
Timeout: 5s
Context created with cancel/timeout
1

Create Context

Parent creates context with cancel or timeout.

1 / 4

Basic Implementation

Context with cancellation signal:

main.go
Loading editor...

Real-World Example: Timeout Handling

HTTP-style request with timeout:

main.go
Loading editor...