Context package
Context
Section titled “Context”The context package provides a standard way to carry deadlines, cancellation signals, and request‑scoped values across API boundaries. It is especially useful for cancelling goroutines.
Example
Section titled “Example”Use context.WithCancel to cancel a goroutine.
Code example
Section titled “Code example”package main
import ( "context" "fmt" "time")
func worker(ctx context.Context, id int) { for { select { case <-ctx.Done(): fmt.Printf("Worker %d cancelled\n", id) return default: fmt.Printf("Worker %d working\n", id) time.Sleep(500 * time.Millisecond) } }}
func main() { ctx, cancel := context.WithCancel(context.Background()) go worker(ctx, 1) go worker(ctx, 2)
time.Sleep(2 * time.Second) cancel() // stop all workers time.Sleep(500 * time.Millisecond)}Output (example)
Section titled “Output (example)”Worker 2 workingWorker 1 workingWorker 1 workingWorker 2 workingWorker 1 workingWorker 2 workingWorker 2 cancelledWorker 1 cancelled