cpp20 · advanced
C++20 jthread & stop_token — RAII Threads with Cooperative Cancellation
std::jthread (C++20) is std::thread with two additions: RAII semantics (the destructor calls request_stop() then join(), eliminating the std::terminate pitfall of forgotten joins) and a built-in stop_source/stop_token for cooperative cancellation. The worker function can take std::stop_token as its first parameter; it polls stoken.stop_requested() in its work loop to detect when the owner wants to stop. Calling t.request_stop() sets the flag atomically. std::stop_callback registers a function to be called synchronously when stop is requested — ideal for waking a condition_variable or cancelling an I/O wait. Use condition_variable_any::wait(lock, stoken, pred) for cancellable waits. Prefer jthread over std::thread for all threads you own.
std::jthread (C++20) wraps std::thread with RAII join and a built-in stop_source; ~jthread calls request_stop() then join() automatically; the worker polls stoken.stop_requested() for cooperative cancellation; stop_callback enables reactive (non-polling) cancellation.
The code
#include <stop_token>#include <thread>
// std::jthread = std::thread + RAII join + stop_token
// Worker that checks stop_token cooperativelyvoid worker(std::stop_token stoken, int id) { while (!stoken.stop_requested()) { doWork(id); // actual work } cleanup(); // runs before thread exits}
// Owner creates jthread — joins automatically on destructionvoid runPipeline() { std::jthread t1(worker, 1); // starts immediately std::jthread t2(worker, 2); doOtherWork();} // ← ~jthread: calls t2.request_stop(), t2.join()// then t1.request_stop(), t1.join() (RAII order)
// Manual stop also possible:std::jthread t(worker, 3);t.request_stop(); // signal stopt.join(); // wait (or just let ~jthread do it)
// stop_callback: called when stop is requestedstd::stop_callback cb(t.get_stop_token(), [] { notifyUI(); });What this lesson walks through
- 01The std::thread join/detach problem
- 02std::jthread — RAII thread that joins in destructor
- 03stop_token — cooperative cancellation signal
- 04request_stop() — signal the worker to stop
- 05~jthread destructs — RAII join, no std::terminate
- 06stop_callback — reactive cancellation
- 07jthread golden rules
std::thread (C++11) requires you to call either join() or detach() before the thread object destructs. If you forget — for example because an exception exits the scope early — the destructor calls std::terminate(). This is the most common concurrency bug in C++11/14 codebases.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++20 jthread & stop_token — RAII Threads with Cooperative Cancellation and 100+ animated C++ interview lessons.