Conceptadvanced
Thread interruption
Also called interrupting a thread, thread cancellation, cooperative cancellation, stop a thread, Thread.interrupt, InterruptedException, CancellationToken, stop_token, request_stop, pthread_cancel, Thread.stop.
Thread interruption asks a running thread to stop. The thread checks for the request and stops by itself, because killing a thread from outside can leave locks held and data half changed.
- Applies to
- core-languages
Idea
Sometimes a thread must stop before its work is done. The user cancels a download, a server shuts down, or another thread already found the answer. Thread interruption is a way to ask the thread to stop. The Java tutorial calls an interrupt "an indication to a thread that it should stop what it is doing and do something else".1
The important word is ask. In most modern APIs, the thread that wants the stop only sends a request, and the target thread decides when and how to stop. .NET calls this "cooperative cancellation": "Cancellation is cooperative and is not forced on the listener".2 The reason is that a thread killed at a random point can leave shared data broken. Java removed Thread.stop because "it was inherently unsafe".3
How it works
A request and a check
Cooperative interruption has two parts:32
- The request. One thread sets a flag that the target thread can see. The flag can be a plain variable, Java's interrupt status, a .NET
CancellationToken, a Gocontext.Contextor a C++std::stop_token. - The check. The target thread checks the flag at points where it is safe to stop. When it sees the request, it cleans up and returns.
The Java documentation describes the simplest form. Code "simply modifies some variable to indicate that the target thread should stop running".3 The target thread "should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running".3 A long calculation checks the flag in its loop. In Java, it can "periodically invoke Thread.interrupted" and return when the result is true.1
Waking a thread that waits
A thread that sleeps or waits does not check a flag. So a good interruption API also wakes the thread:
- Java. If a thread is blocked in
sleep,waitorjoin,interrupt()clears its "interrupt status" and the thread "will receive an InterruptedException".4 Many methods that throw this exception "are designed to cancel their current operation and return immediately when an interrupt is received".1 - .NET. A thread can wait on
CancellationToken.WaitHandletogether with another event, so a cancellation ends the wait.2 - C++. A
std::stop_tokencan be passed "to the interruptible waiting functions of std::condition_variable_any", which ends the wait when a stop is requested.5 - Go. A goroutine waits in a
selectonctx.Done()and on its other channels. TheDonechannel closes when the cancel function is called.6
The examples show this. Each worker starts a wait of 10 seconds, and the main thread then asks it to stop. The worker wakes, prints a message and ends in well under 1 second.
Forced stops
Some systems can also stop a thread from outside, without its help. This is almost always unsafe:
- Locks and broken data. Java's
Thread.stopmade the thread unlock all of its monitors. If an object that a monitor protected was half changed, "other threads may have viewed these objects in an inconsistent state".3 The thread could be stopped "almost anywhere", so code could not clean up reliably.3 - Locks that stay locked. Windows
TerminateThreaddoes the opposite. If the target thread owns a critical section, "the critical section will not be released", and if it is allocating memory, "the heap lock will not be released".7 - No defense. "A thread cannot protect itself against TerminateThread", other than by controlling access to its handles.7
POSIX pthread_cancel is between the two kinds. It sends a request, and "The target thread's cancelability state and type determines when the cancellation takes effect". Before the thread ends, its cleanup handlers and the destructors of its thread-specific data run.8
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Absent | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Standard library | POSIX has pthread_cancel, which runs the cleanup handlers of the thread. No separate example file. Alternative: A stop flag in an atomic variable, like the stop token in the C++ example. |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | TypeScript runs on a JavaScript engine and uses the same Node.js worker API. No example file exists. Alternative: Worker.terminate() or a stop flag in a SharedArrayBuffer, as in the JavaScript example. |
| Go | Standard library | |
| Rust | Absent | |
| Kotlin | Standard library | On the JVM, Kotlin uses the Java Thread.interrupt, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | A query has no threads. |
| Bash | Does not apply | A Bash script runs in one thread for each process. |
| PowerShell | Standard library | PowerShell runs on .NET and can use its CancellationToken; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no threads. |
| CSS | Does not apply | Style rules have no threads. |
| Regular expressions | Does not apply | A pattern has no threads. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | absent | no interrupt; a stop flag such as threading.Event |
| JavaScript | stdlib | worker.terminate(); a flag in a SharedArrayBuffer |
| TypeScript | stdlib | as JavaScript |
| Java | stdlib | Thread.interrupt, InterruptedException |
| Kotlin | stdlib | the Java Thread.interrupt on the JVM |
| C# | stdlib | CancellationTokenSource, CancellationToken |
| Go | stdlib | context.WithCancel, ctx.Done() |
| Rust | absent | a stop flag such as AtomicBool; park and unpark |
| C | stdlib | pthread_cancel in POSIX |
| C++ | stdlib | std::jthread, std::stop_source, std::stop_token |
| Bash | n/a | one thread for each process |
| PowerShell | stdlib | the .NET CancellationToken |
| SQL | n/a | a query has no threads |
| Regex | n/a | a pattern has no threads |
| HTML/CSS | n/a | markup and style rules have no threads |
- Python. Threads "cannot be destroyed, stopped, suspended, resumed, or interrupted".9 To stop a thread "gracefully", the documentation says to use "a suitable signalling mechanism such as an Event".9
- Java.
interrupt()sets the interrupt status of the thread, or wakes it from a blocking call with anInterruptedException.4Thread.stopis deprecated for removal, and in Java 21 it throwsUnsupportedOperationExceptionalways.4 - C#. The code that starts the work creates a
CancellationTokenSourceand passes its token to each thread or task. A listener can notice a request "by polling, callback registration, or waiting on wait handles".2Thread.Abort"throws a PlatformNotSupportedException at run time on .NET 5 and later and .NET Core".10 - Go. A
Contextcarries "cancellation signals", and "When a Context is canceled, all Contexts derived from it are also canceled".6 So one cancel can stop a whole tree of goroutines. - Rust. The
std::threadmodule can spawn, sleep, park and join threads, but it has no function to stop another thread.11 The example uses anAtomicBoolandpark_timeout. - C++.
std::jthread"can be cancelled/stopped in certain situations". It holds astd::stop_sourceand passes astd::stop_tokento the thread function.12 Its destructor asks the thread to stop and joins it.12 - JavaScript. Node.js
worker.terminate()will "Stop all JavaScript execution in the worker thread as soon as possible".13 A worker shares memory only "by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances", so a forced stop can leave only that shared memory half changed.13
import threading
import time
stop = threading.Event()
rounds = 0
def worker():
global rounds
while not stop.is_set():
rounds += 1
# Event.wait sleeps, but it returns at once when the event is set.
stop.wait(10)
print("worker: stop requested, cleaning up")
t = threading.Thread(target=worker)
t.start()
time.sleep(0.1)
start = time.perf_counter()
stop.set()
t.join()
print("worker stopped in under 1 s:", time.perf_counter() - start < 1)
print("worker alive after join:", t.is_alive())
worker: stop requested, cleaning up
worker stopped in under 1 s: True
worker alive after join: False
- Verdict: absent. Python threads "cannot be destroyed, stopped, suspended, resumed, or interrupted". The worker must stop by itself.
- The Python documentation says: "If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event". The example uses an
Eventas the stop flag. stop.wait(10)sleeps liketime.sleep(10), but it returns at once when the main thread callsstop.set(). So the worker stops in well under 1 second.- A daemon thread does not stop when it is asked to. It is "abruptly stopped at shutdown", and its resources "may not be released properly".
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <stop_token>
#include <thread>
int main() {
using namespace std::chrono_literals;
std::mutex m;
std::condition_variable_any cv;
std::chrono::steady_clock::time_point start;
{
std::jthread worker([&](std::stop_token st) {
std::unique_lock lock(m);
// Waits for up to 10 s, but a stop request ends the wait at once.
cv.wait_for(lock, st, 10s, [] { return false; });
std::cout << "worker: stop requested: " << std::boolalpha << st.stop_requested() << '\n';
});
std::this_thread::sleep_for(100ms);
start = std::chrono::steady_clock::now();
worker.request_stop();
} // The jthread destructor joins the thread.
std::cout << "worker stopped in under 1 s: " << std::boolalpha
<< (std::chrono::steady_clock::now() - start < 1s) << '\n';
}
worker: stop requested: true
worker stopped in under 1 s: true
- Verdict: stdlib.
std::jthread"can be cancelled/stopped in certain situations". It holds astd::stop_source, and it passes astd::stop_tokento the thread function. request_stop()sets the stop state. Thestd::stop_tokencan be passed "to the interruptible waiting functions of std::condition_variable_any", so the 10-second wait ends at once.- The jthread destructor joins the thread, so the worker has finished when the last line prints.
- "Unlike std::thread , the jthread logically holds an internal private member of type std::stop_source". Code that uses a plain
std::threadneeds its own flag, such as astd::atomic<bool>.
public class Main {
public static void main(String[] args) throws InterruptedException {
// A thread that sleeps: interrupt() wakes it with an InterruptedException.
Thread sleeper = new Thread(() -> {
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
System.out.println("sleeper: interrupted, cleaning up");
System.out.println("interrupt status after the exception: "
+ Thread.currentThread().isInterrupted());
}
});
sleeper.start();
Thread.sleep(100);
long start = System.nanoTime();
sleeper.interrupt();
sleeper.join();
System.out.println("sleeper stopped in under 1 s: "
+ (System.nanoTime() - start < 1_000_000_000L));
// A thread that only calculates must check its interrupt status itself.
Thread counter = new Thread(() -> {
long n = 0;
while (!Thread.currentThread().isInterrupted()) {
n++;
}
System.out.println("counter: saw the interrupt status, stopping");
});
counter.start();
Thread.sleep(100);
counter.interrupt();
counter.join();
System.out.println("both threads alive: " + (sleeper.isAlive() || counter.isAlive()));
}
}
sleeper: interrupted, cleaning up
interrupt status after the exception: false
sleeper stopped in under 1 s: true
counter: saw the interrupt status, stopping
both threads alive: false
- Verdict: stdlib.
Thread.interruptasks a thread to stop. The tutorial calls an interrupt "an indication to a thread that it should stop what it is doing and do something else". - The sleeper is blocked in
sleep, so "its interrupt status will be cleared and it will receive an InterruptedException". The second line printsfalsefor this reason. - The counter never calls a method that throws
InterruptedException, so it checksisInterrupted()in its loop. Without that check,interrupt()would only set the status, and the loop would never end. Thread.stopis not an alternative. It is deprecated for removal, and the documentation says: "It was inherently unsafe."
using System.Diagnostics;
using var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
var worker = new Thread(() =>
{
while (!token.IsCancellationRequested)
{
// Waits up to 10 s, but wakes at once when cancellation is requested.
token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
}
Console.WriteLine("worker: cancellation requested, cleaning up");
});
worker.Start();
Thread.Sleep(100);
var watch = Stopwatch.StartNew();
cts.Cancel();
worker.Join();
Console.WriteLine($"worker stopped in under 1 s: {watch.Elapsed < TimeSpan.FromSeconds(1)}");
Console.WriteLine($"worker alive after join: {worker.IsAlive}");
worker: cancellation requested, cleaning up
worker stopped in under 1 s: True
worker alive after join: False
- Verdict: stdlib. .NET has "a unified model for cooperative cancellation" that uses a cancellation token. The code that owns the
CancellationTokenSourcecallsCancel, and the worker checksIsCancellationRequested. - The worker waits on
token.WaitHandle, so the wait ends when cancellation is requested. The documentation lists polling, callbacks and wait handles as the ways to listen. using var ctsdisposes the token source at the end. The documentation says to callDispose"when you have finished using the cancellation token source".Thread.Abortis not an alternative. It "throws a PlatformNotSupportedException at run time on .NET 5 and later and .NET Core".
import { Worker } from "node:worker_threads";
// A stop flag in shared memory. The worker checks it and stops by itself.
const flag = new Int32Array(new SharedArrayBuffer(4));
const polite = new Worker(
`
const { workerData, parentPort } = require("node:worker_threads");
const flag = new Int32Array(workerData);
// Atomics.wait sleeps for up to 10 s, but Atomics.notify wakes it early.
while (Atomics.load(flag, 0) === 0) Atomics.wait(flag, 0, 0, 10000);
parentPort.postMessage("worker: stop requested, cleaning up");
`,
{ eval: true, workerData: flag.buffer },
);
polite.on("message", (m) => console.log(m));
await new Promise((resolve) => setTimeout(resolve, 100));
const start = performance.now();
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0);
await new Promise((resolve) => polite.once("exit", resolve));
console.log("worker stopped in under 1 s:", performance.now() - start < 1000);
// A worker in an endless loop never checks a flag. terminate() stops it from outside.
const busy = new Worker("for (;;) {}", { eval: true });
await new Promise((resolve) => busy.once("online", resolve));
const code = await busy.terminate();
console.log("busy worker terminated, exit code:", code);
worker: stop requested, cleaning up
worker stopped in under 1 s: true
busy worker terminated, exit code: 1
- Verdict: stdlib. Node.js has two ways to stop a worker. The worker can check a flag and stop by itself, or the main thread can call
worker.terminate(). - The first worker sleeps in
Atomics.wait. The main thread sets the flag and callsAtomics.notify, so the worker wakes at once, posts a message and ends. terminate()will "Stop all JavaScript execution in the worker thread as soon as possible". It returns "a Promise for the exit code", which is 1 here.- Workers share memory only "by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances". So a forced stop cannot leave the other objects of the main thread half updated, but data in a
SharedArrayBuffercan be.
package main
import (
"context"
"fmt"
"time"
)
func worker(ctx context.Context, done chan<- struct{}) {
defer close(done)
for {
select {
case <-ctx.Done():
fmt.Println("worker: stopped because", ctx.Err())
return
case <-time.After(10 * time.Second):
// One step of work would go here.
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go worker(ctx, done)
time.Sleep(100 * time.Millisecond)
start := time.Now()
cancel()
<-done
fmt.Println("worker stopped in under 1 s:", time.Since(start) < time.Second)
}
worker: stopped because context canceled
worker stopped in under 1 s: true
- Verdict: stdlib. A
context.Contextcarries "cancellation signals". The goroutine checks the context and returns by itself. context.WithCancelreturns a context and a cancel function. The context'sDonechannel "is closed when the returned cancel function is called". Theselectin the worker returns when that channel closes.ctx.Err()gives the reason for the stop. Here it printscontext canceled.- "When a Context is canceled, all Contexts derived from it are also canceled", so one
cancel()can stop a tree of goroutines.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
fn main() {
let stop = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&stop);
let worker = thread::spawn(move || {
while !flag.load(Ordering::Acquire) {
// Sleeps for up to 10 s; unpark() wakes it early.
thread::park_timeout(Duration::from_secs(10));
}
println!("worker: stop requested, cleaning up");
});
thread::sleep(Duration::from_millis(100));
let start = Instant::now();
stop.store(true, Ordering::Release);
worker.thread().unpark();
worker.join().unwrap();
println!("worker stopped in under 1 s: {}", start.elapsed() < Duration::from_secs(1));
}
worker: stop requested, cleaning up
worker stopped in under 1 s: true
- Verdict: absent. The
std::threadmodule has functions to spawn, sleep, park and join threads, but none to stop another thread. The example uses anAtomicBoolas a stop flag. thread::park_timeout"Blocks unless or until the current thread’s token is made available or the specified duration has been reached". The main thread sets the flag and then callsunpark, so the worker wakes at once.- The worker checks the flag in a loop, because a parked thread can also wake for other reasons.
- When the main thread of a Rust program ends, other threads are not stopped cleanly: "any destructors on the remaining threads’ stacks may not be executed". The example joins the worker first.
Variations and related ideas
- Deadlines and timeouts. A Go context can also have a deadline: "A Context with a deadline is canceled after the deadline passes".6 The same check then handles both a cancel and a timeout.
- Cancellation trees. Go contexts and .NET linked tokens join requests. A child context is canceled with its parent, and a .NET listener can "listen to multiple tokens simultaneously by joining them into one linked token".62
- Callbacks. Instead of polling, a .NET listener can register a callback, and a C++
std::stop_callbackruns when a stop is requested.25 - Processes instead of threads. Work that may need a forced stop can run in a separate process. See Process-based parallelism.
- Async cancellation. In Async/await code, the same tokens and contexts cancel tasks instead of threads. The .NET model covers "asynchronous or long-running synchronous operations".2
Pitfalls
- A request that nobody checks. An interrupt only sets a flag. "For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption".1 A loop that never checks the flag never stops.
- Swallowing the interrupt. In Java, the
InterruptedExceptionclears the interrupt status.4 Code that catches the exception and does nothing loses the request. Code that cannot rethrow it should callThread.currentThread().interrupt(), so the thread will "reraise the InterruptedException as soon as it is able".3 - A flag that other threads cannot see. A plain variable may not be visible to the other thread at once. In Java, "the variable must be volatile (or access to the variable must be synchronized)".3 Use
Event, an atomic type or a token, as the examples do. - Killing threads. Do not use
Thread.stop,Thread.AbortorTerminateThreadto stop normal work.TerminateThread"is a dangerous function that should only be used in the most extreme cases".7 - Forgetting to cancel. In Go, "Failing to call the CancelFunc leaks the child and its children until the parent is canceled".6
- Daemon threads at exit. In Python, daemon threads "are abruptly stopped at shutdown", and their resources "may not be released properly".9 In Rust, when the main thread ends, "any destructors on the remaining threads’ stacks may not be executed".11
Cost
- Checks. A check of a flag is cheap. .NET says that "Polling itself does not significantly impact performance".2 The developer chooses how often to check, which sets how fast the thread responds.2
- Latency. A thread stops only at its next check or at the end of its current wait. A long step with no checks delays the stop.1
- Code. Every long loop and every wait must handle the request, and the thread must clean up on the way out.3
History
- POSIX.
pthread_cancelwas "First released in Issue 5", for alignment with the POSIX Threads Extension.8 - Java 1.2. Java deprecated
Thread.stopin version 1.2.4 In Java 21, it always throwsUnsupportedOperationException.4 - .NET 5.
Thread.AbortthrowsPlatformNotSupportedExceptionon .NET 5 and later and on .NET Core.10 - C++20.
std::jthreadandstd::stop_tokencame with C++20.125
References
- The Java Tutorials, Interrupts, introduction; Supporting Interruption; The Interrupt Status Flag
- Microsoft Learn, Cancellation in managed threads, introduction; Listening by Polling; Listening by Using a Wait Handle
- Java SE 21, Java Thread Primitive Deprecation, Why is Thread.stop deprecated; What should I use instead of Thread.stop; How do I stop a thread that waits for long periods
- Java SE 21 API, java.lang.Thread, stop; interrupt; interrupted
- cppreference, std::stop_token, description; Notes
- Go standard library, package context, Overview; func WithCancel
- Microsoft Learn, TerminateThread function, Remarks
- POSIX.1-2024, pthread_cancel, DESCRIPTION; RATIONALE; CHANGE HISTORY
- The Python Standard Library, threading, introduction; Thread objects; Event objects
- Microsoft Learn, Thread.Abort method, Remarks
- Rust standard library, module std::thread, module description; Functions
- cppreference, std::jthread, description
- Node.js documentation, Worker threads, introduction; worker.terminate()
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag CT7Y2C Edit this page History Report an error Markdown