std::thread, std::jthread, stop_token
advanced10 min readLesson 163 of 204
Ownership of a thread, automatic joining, and cooperative cancellation โ the modern lifecycle.
std::thread: you own it
A std::thread runs your callable immediately. Forgetting join() or detach() before destruction calls std::terminate โ ownership is explicit and unforgiving. Scope threads tightly and join unconditionally.
std::jthread: the RAII thread (C++20)
std::jthread auto-joins in its destructor and carries a std::stop_token for cooperative cancellation:
std::jthread worker([](std::stop_token st) {
while (!st.stop_requested()) {
// do a unit of work
}
});
// ... destructor requests stop AND joins โ no terminate on scope exit
Cancellation is cooperative: the thread decides where checking stop_requested() is safe. Nothing preempts your code.
The graded discipline
Every thread/jthread a function creates must be joined (or handed to an owner that will). The exercises verify by side effects: results written before join, no leaked running threads at scope exit.