On this page
std::jthread (C++20)
Prev: concurrency | Up: concurrency | Next: std::mutex & std::scoped_lock
Rel: std::thread, RAII & Destructors, jthread Work Queue Tutorial
Ref: cppreference — std::jthread
Tags: #public #prog #cpp #stdlib #concurrency #tier/core
Overview
std::jthread (<thread>, C++20) is an RAII-safe upgrade to std::thread: its destructor automatically calls request_stop() and join(), eliminating std::terminate() crashes on forgotten joins, and it supports built-in cooperative cancellation via std::stop_token.
Notes & Pitfalls
- Prefer
std::jthreadoverstd::threadin C++20+: Automatically joins in its destructor (never callsstd::terminate) and passes a built-instd::stop_tokenfor cooperative cancellation.
Example
#include <atomic>
#include <cassert>
#include <thread>
int main() {
std::atomic<int> done{0};
{
std::jthread worker([&](std::stop_token st) {
if (!st.stop_requested()) done.store(1);
});
} // automatically requests stop and joins here
assert(done.load() == 1);
}
Linked from
Related notes
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/thread Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib
- tuts/cpp/tutorials/jthread_work_queue_and_atomics Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #tier
- tuts/cpp/builtins/raii_and_destructors Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/concurrency/atomic shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/find_if shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform shared tags: #cpp, #prog, #stdlib, #tier