Skip to content

std::jthread (C++20) ​

One-Liner ​

A thread class with built-in RAII semantics — on destruction it automatically sends a stop request and joins, wiping out the crashes caused by forgetting to join.

#include <thread>

Core API Cheat Sheet ​

OperationSignatureDescription
Construct (with function)template<class F> jthread(F&& f, Args&&... args)Starts a new thread executing f(args...)
Construct (with stop_token)template<class F> jthread(F&& f)f's first parameter receives std::stop_token
Destructor~jthread()Requests stop + joins (if joinable)
Request stopbool request_stop() noexceptRequests cooperative stop, returns whether it succeeded
Get stop tokenstd::stop_token get_stop_token() const noexceptGets the current thread's stop token
Wait for completionvoid join()Blocks until the thread finishes
Detach threadvoid detach()Detaches; the thread then runs independently
Is joinablebool joinable() const noexceptChecks whether the thread is joinable
Get IDstd::thread::id get_id() const noexceptReturns the thread identifier

Minimal Example ​

C++
// Standard: C++20
#include <iostream>
#include <thread>

void worker(std::stop_token st) {
    while (!st.stop_requested()) {
        std::cout << "working...\n";
    }
    std::cout << "stopped\n";
}

int main() {
    std::jthread t(worker); // stop_token is passed in automatically
    // t's destructor automatically calls request_stop() + join()
} // Output: working... stopped

Embedded Applicability: Medium ​

  • The RAII automatic join eliminates the hazard of forgetting to join, improving code robustness.
  • The std::stop_token cooperative cancellation mechanism is more disciplined than hand-rolled flag variables.
  • Depends on OS thread support; bare-metal RTOS scenarios require a thread abstraction layer alongside it.
  • Requires C++20 standard library support; available from GCC 10+, but Clang/libc++ support came later (17+).

Compiler Support ​

GCCClangMSVC
101719.28

See Also ​


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05