Header Reference: <thread>
Header Reference: <thread>
The main thread and stop-token facilities from the standard thread header.
Header Reference: <thread>
The main thread and stop-token facilities from the standard thread header.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
Header reference pages are meant to answer a practical question quickly: what this header provides, when to reach for it, and which usage rules are easiest to get wrong.
<thread>std::threadstd::jthreadstd::this_thread namespace helpersstd::stop_source, std::stop_token, std::stop_callbackstd::thread must be joined or detached before destructionstd::jthread joins automatically and is often the safer defaultstd::thread is only an execution handle; synchronization still lives in other headersstd::jthread pairs thread lifetime with cooperative stop requests, which often simplifies shutdown logicstd::ref#include <thread>
int main() {
int steps = 0;
std::jthread worker([&](std::stop_token token) {
while (!token.stop_requested() && steps < 1) {
++steps;
}
});
worker.request_stop();
return 0;
}
<mutex> for mutual exclusion<condition_variable> for blocking waits<future> for async result passing<atomic> for lock-free atomic state#include <thread>
int main() {
std::jthread worker([](std::stop_token token) {
while (!token.stop_requested()) {
break;
}
});
worker.request_stop();
}