C++C++ Explainer
C++ · 6 · Concurrency29 / 36 · 81%

jthread, stop_token & Coroutines

C++20's answer to "I forgot to join" and to callback-heavy async code.

Examples: jthread, stop_token, co_await, co_yield

shortcuts: ← prev · → next · M mark
1

std::jthread

Joins automatically in its destructor and supports cooperative cancellation.

Example
example
std::jthread worker([](std::stop_token st) {
    while (!st.stop_requested()) {
        do_chunk();
    }
});
// worker.request_stop() then join() happen automatically at scope exit
std::thread
caseresult
forgot join()std::terminate
exception thrownterminate
cancellationroll your own
→
std::jthread
caseresult
scope exitauto join
exceptionauto join
cancellationstop_token
2

Cooperative Cancellation

There is no safe way to kill a thread — you ask it to stop.

Example
example
void worker(std::stop_token st) {
    std::stop_callback cb(st, []{ std::puts("stopping"); });
    while (!st.stop_requested()) { step(); }
}
3

Coroutines

A function that can suspend and resume — the compiler rewrites it into a state machine.

Example
example
Generator<int> fibonacci() {
    int a = 0, b = 1;
    while (true) {
        co_yield a;             // suspend, hand a value out
        auto next = a + b; a = b; b = next;
    }
}

Task<Response> fetch(Url u) {
    auto conn = co_await connect(u);   // suspend without blocking a thread
    co_return co_await conn.read();
}
WATCH OUT
C++20 ships the language machinery but almost no library types — you write or import Task/Generator (C++23 adds std::generator).
4

When to Use What

Match the tool to the workload.

Complexity
jthreadCPU-bound parallelism
async/futureone-off background result
thread poolmany short tasks
coroutinesI/O-bound concurrencythousands of in-flight ops