Skip to content

std::jthread (C++20)

In a Nutshell

A thread class with built-in RAII semantics — on destruction it automatically sends a stop request and joins, eliminating crashes from forgotten joins.

#include <thread>

Core API Quick Reference

OperationSignatureDescription
Construct with functiontemplate<class F> jthread(F&& f, Args&&... args)Start a new thread executing f(args...)
Construct with stop_tokentemplate<class F> jthread(F&& f)f's first argument receives std::stop_token
Destructor~jthread()Request stop + join (if joinable)
Request stopbool request_stop() noexceptRequest cooperative stop, returns success
Get stop tokenstd::stop_token get_stop_token() const noexceptGet the thread's stop token
Wait for completionvoid join()Block until thread finishes
Detach threadvoid detach()Detach; thread runs independently
Is joinablebool joinable() const noexceptCheck if thread can be joined
Get IDstd::thread::id get_id() const noexceptReturn 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 is passed automatically
    // t destructor calls request_stop() + join() automatically
} // Output: working... stopped

Embedded Applicability: Medium

  • RAII auto-join eliminates the risk of forgotten joins, improving robustness
  • std::stop_token cooperative cancellation is more disciplined than hand-rolled flag variables
  • Requires OS thread support; bare-metal RTOS scenarios need a threading abstraction layer
  • Requires C++20 standard library support; GCC 10+ works, but Clang/libc++ support came later (17+)

Compiler Support

GCCClangMSVC
101719.28

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress