Skip to content
Tutorials Center
My learning

Topics

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.

Go
ctx, cancel := context.WithCancel(parent)
defer cancel()

Try it

Go Stop a producer when the consumer is done

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.

Go First result wins, with a cause

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

Go
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 cancel more 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.
  • cancel does not wait for goroutines to finish; combine with a sync.WaitGroup if 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, and go vet warns when you forget.
  • Cancelling is a signal, not a kill. Goroutines must watch ctx.Done() (usually in a select) or pass ctx to APIs that do.
  • Whoever creates the context calls cancel. Passing the CancelFunc around widely makes ownership murky; hand out the ctx instead.
  • Goroutine leaks: a producer blocked on ch <- v never exits unless it also selects on ctx.Done(), as in the first example.
  • context.Cause is 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 WithTimeout instead of a timer plus cancel.