Skip to content

std::jthread (C++20)

In a Nutshell

A thread class with built-in RAII semantics—automatically sends a stop request and joins on destruction, eliminating 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 argument receives std::stop_token
Destructor~jthread()Requests stop + join (if joinable)
Request stopbool request_stop() noexceptRequests cooperative stop, returns success status
Get stop tokenstd::stop_token get_stop_token() const noexceptGets the current thread's stop token
Wait for completionvoid join()Blocks waiting for thread to finish
Detach threadvoid detach()Detaches, thread runs independently
Is joinablebool joinable() const noexceptChecks if thread is joinable
Get IDstd::thread::id get_id() const noexceptReturns thread identifier

Minimal Example

cpp
// 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
    // t 析构时自动 request_stop() + join()
} // 输出: working... stopped

Embedded Applicability: Medium

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

Compiler Support

GCCClangMSVC
101719.28

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05