Go Reference ยท Concurrency and Context
Go context.WithCancel() function
Reference for Go context.WithCancel and WithCancelCause: derive a cancellable child context, stop goroutines by calling cancel, and avoid leaked contexts.
context.WithCancel returns a copy of a parent context together with a cancel function. Calling cancel closes the child's Done channel and sets its Err to context.Canceled. Every context derived from that child is cancelled too. The child is also cancelled if the parent is.
Use it to give a group of goroutines a single "stop now" switch: the first worker that finds a result, a failed step in a pipeline, or a user pressing Ctrl+C can call cancel and everyone else winds down.
ctx, cancel := context.WithCancel(parent) defer cancel()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) type CancelFunc func() type CancelCauseFunc func(cause error)
| Name | Description |
|---|---|
parent |
The context to derive from; must not be nil. |
Returns. The child context and a function that cancels it. With WithCancelCause (Go 1.20) the function takes an error that context.Cause(ctx) returns later, while ctx.Err() is still context.Canceled.
Edge cases.
- Calling
cancelmore than once is safe; only the first call has an effect (and, for the cause variant, only the first cause is recorded). - If the parent is already cancelled, the child is born cancelled.
canceldoes not wait for goroutines to finish; combine with async.WaitGroupif you need that.
Usage notes
- Always call
cancel, even on the happy path. Skipping it leaks the child context until the parent is cancelled.defer cancel()right after creation is the idiom, andgo vetwarns when you forget. - Cancelling is a signal, not a kill. Goroutines must watch
ctx.Done()(usually in aselect) or passctxto APIs that do. - Whoever creates the context calls
cancel. Passing theCancelFuncaround widely makes ownership murky; hand out thectxinstead. - Goroutine leaks: a producer blocked on
ch <- vnever exits unless it also selects onctx.Done(), as in the first example. context.Causeis the way to tell "why" apart when several things can cancel;errors.Is(ctx.Err(), context.Canceled)only tells you "it was cancelled".- Timeouts: for time limits use
WithTimeoutinstead of a timer pluscancel.