Skip to content

Cancellation

Category: Async · Status: stub · Lessons: chapter 06, Async (planned)

One line: Asking a running task to stop early and release what it holds; in most languages the task has to cooperate by noticing the request.

Also called: cancellation token, context cancellation, stop token.

How it connects

flowchart LR
  n_cancellation["Cancellation"]
  n_task_leak["Leaked tasks"]
  n_structured_concurrency["Structured concurrency"]
  n_timeout["Timeout"]
  n_cancellation -->|prevents| n_task_leak
  n_structured_concurrency -->|uses| n_cancellation
  n_timeout -->|uses| n_cancellation
  classDef center stroke-width:3px
  class n_cancellation center
  classDef outside stroke-dasharray: 4 3
  class n_task_leak,n_structured_concurrency,n_timeout outside

In each language

Rust a future is cancelled by dropping it; tokio's select! cancels the branches that lose that way, which is why its docs discuss cancellation safety
Go a context: calling cancel closes the context's Done channel, and with it those of the contexts derived from it; each goroutine has to watch Done
C pthread_cancel asks; the target thread's cancelability state and type decide when it takes effect
C++ std::stop_token (C++20) tells a thread whether a stop has been requested; a std::jthread can be stopped this way
Java Thread.interrupt, which a blocked sleep, wait or join answers with InterruptedException; Future.cancel
Python Task.cancel raises CancelledError inside the task at its next opportunity
C# a CancellationToken, a cooperative model: each listener must notice the request and respond to it
JavaScript an AbortController and its AbortSignal
Kotlin cooperative ↗: a coroutine reacts to cancellation only when it suspends or checks for it explicitly
Swift cooperative: a task checks with Task.checkCancellation() or Task.isCancelled (Swift book ↗)
Erlang and Elixir Process.exit/2 sends an exit signal; a process that traps exits receives it as a message instead
Haskell killThread raises the ThreadKilled exception in the target thread

Where to read more