On this page
  1. std::jthread (C++20)
  2. Overview
  3. Notes & Pitfalls
  4. Example

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

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