What does C++20 std::jthread do differently from std::thread, and how does a worker function receive and use its std::stop_token?
answer
- a destructor that cooperates
- request_stop, then join
- token as the first parameter
- polling, not forced cancellation
basics
~10 sC++20 std::jthread owns a stop_source; its destructor calls request_stop() and then join() instead of terminating. If the function's first parameter accepts a std::stop_token, jthread passes one, and the worker polls stop_requested() to exit cooperatively.
solid answer
~40 s`std::jthread` (C++20, `<thread>` with `<stop_token>`) is a `std::thread` plus a `std::stop_source`. Its constructor calls `f(get_stop_token(), args...)` when that is well-formed and `f(args...)` otherwise, so a worker opts in simply by taking a `std::stop_token` first. Its destructor and its move assignment, when joinable, call `request_stop()` and then `join()` rather than `std::terminate`. Stopping is **cooperative**: nothing interrupts the thread; the worker checks `st.stop_requested()` at safe points, registers a `std::stop_callback`, or waits through an interruptible wait that takes the token. A worker that never looks at its token turns the destructor into an indefinite join. A stop request cannot be withdrawn, and `get_stop_source()` lets other code, such as a cancel button, request the stop earlier.
code
cpp · 21 lines#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>
#include <vector>
void transcode(std::stop_token st, int segment) {
while (!st.stop_requested()) { // poll between chunks
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
std::cout << "segment " << segment << " cancelled\n";
}
int main() {
std::vector<std::jthread> workers;
for (int seg = 0; seg < 3; ++seg)
workers.emplace_back(transcode, seg); // jthread passes get_stop_token() first
std::this_thread::sleep_for(std::chrono::milliseconds(20));
// User pressed Cancel: leaving main destroys the vector, and each
// ~jthread() calls request_stop() and then join().
}go deeper
Know that C++20 std::jthread joins in its destructor and can pass a std::stop_token to its function.
Explain the request_stop-then-join destructor, how the token reaches the first parameter, and why stopping is cooperative.
Design shutdown so every jthread worker checks its token at bounded intervals, and order members so the thread joins before its data dies.
Decide whether a codebase standardizes on jthread and stop tokens or a shared cancellation type, given C++17 targets still in the build.
## Two problems std::thread leaves to you A `std::thread` has no built-in way to ask its function to stop, and it terminates the program if it is destroyed while joinable. Before C++20 every codebase wrote the same two pieces by hand: a `std::atomic<bool>` stop flag shared with the worker, and an RAII guard that sets the flag and joins. **C++20 standardized both** as `std::jthread` and the stop-token types in `<stop_token>`. ## What std::jthread adds | | `std::thread` | `std::jthread` (C++20) | |---|---|---| | Destructor when joinable | `std::terminate` | `request_stop()`, then `join()` | | Move assignment into a joinable object | `std::terminate` | `request_stop()`, then `join()`, then take the new state | | Stop state | none | owns a `std::stop_source` | | Extra members | none | `get_stop_source()`, `get_stop_token()`, `request_stop()` | | `join()`, `detach()`, `joinable()` | yes | yes, same meaning | A note in the standard adds a subtle point: a jthread's worker can be asked to stop only once, because the stop token it received cannot be replaced. ## How the worker receives its token The constructor tries `invoke(f, get_stop_token(), args...)` first. If that expression is well-formed, the worker gets the token as its first argument; otherwise jthread falls back to `invoke(f, args...)`, exactly like `std::thread`. So the worker signature is the whole opt-in: - `void transcode(std::stop_token st, int segment)` receives a token. - `void transcode(int segment)` is started the same way and never sees one. - `void transcode(std::stop_token& st)` does **not** compile: the token is passed as a prvalue, which a non-const lvalue reference cannot bind. Take it by value; it is a cheap shared handle. ## Cooperative, not preemptive A stop request sets a flag in the shared stop state and runs any registered callbacks. It does not interrupt, signal or kill the thread. Once made it cannot be withdrawn, and later requests return `false`. The worker reacts in one of three ways: 1. **Polling** `st.stop_requested()` between units of work, as the transcoder below does between chunks. 2. **Registering** a `std::stop_callback` that unblocks a blocking call when the stop arrives. 3. **Waiting** with the `std::condition_variable_any::wait` overloads that take a `std::stop_token`, so the wait itself wakes on a stop. A default-constructed `std::stop_token` has no stop state and reports `stop_possible() == false`; the token a jthread passes always has one. ## Sharing one stop source across workers A jthread's own stop source reaches only its own worker. To cancel a whole job with one call, create a `std::stop_source cancel_all` and pass `cancel_all.get_token()` as an ordinary argument. For `void transcode(std::stop_token, int)`, the call with the jthread's token prepended is ill-formed, so jthread falls back to calling `transcode(token, segment)` with the shared token, and one `cancel_all.request_stop()` reaches every worker. The cost: `~jthread()` still requests a stop on its *own* source, which this worker no longer watches, so the owner must request the shared stop before the threads are destroyed. The C++17 equivalent is a `std::atomic<bool>` flag passed by reference plus a guard that sets it and joins; it works, but every team writes it slightly differently and none of them can unblock a waiting thread. ## The transcoder cancel button Each segment worker is a `std::jthread` whose function takes a `std::stop_token` and checks it between chunks. When the user presses Cancel, the UI calls `request_stop()` on each worker (or one shared `std::stop_source` drives all of them), and when the owning object is destroyed the jthread destructors join. There is no flag to forget and no path that terminates. ## Pitfalls - A worker that never checks its token makes `~jthread()` block until the work ends naturally. - Declare a `std::jthread` **member after** the data it uses: members are destroyed in reverse order, so the thread is stopped and joined before that data dies. - `detach()` on a jthread gives up the join, and the destructor of a non-joinable jthread does nothing, so a detached worker never receives the automatic stop request. - `std::jthread` needs `-std=c++20`; libc++ and libstdc++ both ship it, but older toolchains do not.
- What happens if a jthread's function never checks its stop token?The stop request is still recorded, but nothing interrupts the thread, so `~jthread()` waits in `join()` until the function returns on its own. For a long encode that turns a cancel into a hang. Every loop or blocking call in a jthread worker needs a stop check, a `std::stop_callback`, or a stop-aware wait.
- How does a cancel button on another thread reach a jthread's worker?Through the jthread's stop state: call `worker.request_stop()`, or hand the UI a copy of `worker.get_stop_source()` and call `request_stop()` on it. All associated tokens then report `stop_requested() == true`, and a `request_stop()` that returns true synchronizes with a `stop_requested()` call that observes it.
- Why should a std::jthread data member be declared after the members its thread uses?Members are destroyed in reverse declaration order. If the jthread is declared last it is destroyed first, so its destructor stops and joins the worker while the buffers it reads are still alive. Declared first, it would be destroyed last, after those buffers, and the still-running worker would use destroyed objects.
- std::jthread's request_stop() interrupts or kills the running thread.
- A jthread worker must take std::stop_token& so it sees later requests.
- A stop request can be reset so the same jthread can be restarted.
- std::jthread is available in C++17 under the <thread> header.
- std::jthread's destructor detaches the thread instead of joining it.
Assumes C++20, which added std::jthread and <stop_token>; C++17 code needs std::thread plus a hand-written atomic flag and joining guard.