OSC++.039 explains how a C++20 application can ask a worker to stop without forcibly terminating its thread. std::jthread owns a thread and joins it automatically when the handle is destroyed; std::stop_token lets the worker observe a cooperative stop request. Earlier, OSC++.038 examined asynchronous tasks and futures. The new challenge is managing the lifetime of a long-running worker, including shutdown when an application or test ends.
Why a joining thread differs from std::thread
C++20 introduced std::jthread to reduce lifetime hazards associated with manual joins. Destroying a joinable std::thread calls std::terminate. Destroying a joinable std::jthread instead calls request_stop() and then join(). The behavior appears in the jthread reference and proposal P0660R8. A joining destructor improves cleanup but does not guarantee prompt completion when a worker ignores stop requests or blocks indefinitely.
The callable can accept a std::stop_token as its first parameter. The token observes a shared stop state, and worker.request_stop() marks the request. A worker must check that state or wait using a stop-aware operation. Calling request_stop() does not kill a thread, discard pending writes, or force an arbitrary blocking system call to return. The stop-token reference details the query methods.
Compile a reproducible example
The following standalone program uses a ten-millisecond work interval and requests a stop after a short delay. The counter is atomic because two threads access it. Compile with a C++20-capable toolchain. The editorial build succeeded locally using GCC and strict compiler warnings.
#include <atomic>
#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>
int main() {
std::atomic<int> completed{0};
std::jthread worker([&](std::stop_token stop) {
while (!stop.stop_requested()) {
++completed;
std::this_thread::sleep_for(
std::chrono::milliseconds{10});
}
});
std::this_thread::sleep_for(
std::chrono::milliseconds{35});
bool requested = worker.request_stop();
worker.join();
std::cout << "request accepted: " << requested << "\n";
std::cout << "work iterations: "
<< completed.load() << "\n";
}
g++ -std=c++20 -Wall -Wextra -Werror -pthread demo.cpp -o demo
./demo
One local run printed request accepted: 1 and work iterations: 4. The iteration count is **not** a guaranteed result: operating-system scheduling and timer behavior affect it. join() waits for the worker to return, making the final counter read unambiguous. In actual applications, the worker must define safe places to stop after finishing or rolling back important operations.
Cooperative cancellation and blocking waits
A stop request is a signal, not an exception and not a forced process interruption. A worker that sleeps for a long interval with std::this_thread::sleep_for normally notices the request only after waking. For producer-consumer queues, std::condition_variable_any offers C++20 stop-token-aware wait overloads, allowing a waiting worker to awaken when cancellation is requested. Conventional blocking APIs and std::condition_variable do not automatically become cancellation-aware.
A std::stop_source can request a stop for associated tokens outside a jthread. std::stop_callback registers an action that can run when the request occurs; its execution context demands care, because callbacks may execute on the thread issuing the request. Avoid slow, reentrant or lock-unsafe work inside such callbacks. See the source reference and callback reference.
Thread lifetime is not data-race protection
Automatic joining only manages lifecycle. It cannot make shared counters, queues or application state inherently thread-safe. The example uses std::atomic; more complex data may require a mutex or another synchronization strategy. OSC++.037 on packaged tasks explains another approach to asynchronous results and exceptions, while OSC++.036 on move-only callables introduces callback ownership. Workers that throw uncaught exceptions can still terminate a program despite using jthread.
Practice: plan a safe shutdown
Consider a fictional device-monitoring worker that periodically polls a development simulator and writes status records. Identify where to check the stop token, where to finish an in-flight record, and which shared state needs synchronization. Explain why a blocked network operation may need an explicit cancellation facility or a bounded timeout. Then change the demonstration program’s sleep interval and compare results without treating a fixed iteration count as proof of correctness.
Takeaway: std::jthread manages joining and exposes a cooperative stop mechanism. Correct shutdown still depends on worker cooperation, safe blocking behavior, thread-safe data, and clear ownership. The OSC++.033 callable lesson provides a useful refresher on the function objects passed into modern concurrency APIs.
Editor’s Note: Standards behavior was checked against C++ proposal P0660R8, cppreference and vendor-neutral library documentation. The local example compiled using GCC in C++20 mode with -Wall -Wextra -Werror -pthread and ran successfully; results involving thread timing vary. Three educational YouTube video pages were verified, but actual playback and mobile rendering were not independently tested. The 1200 × 630 original photorealistic cover uses illustrative code and depicts no actual production system.
We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

Disclaimer: Educational programming material only. Run examples in an authorized development environment. No production thread management, engineering certification, financial advice or investment recommendation is implied.

Leave a Reply