Daily C++ Tip 6

A thread that stops itself cleanly (std::jthread)

A jthread joins on destruction and stops through its stop token.

std::jthread joins at destruction and carries a stop token, so the two classic thread bugs — a forgotten join and a thread with no way to stop — are both gone by construction.

#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>

int main() {
    std::jthread worker([](std::stop_token st) {
        while (!st.stop_requested()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        std::cout << "stopped cleanly\n";
    });
    std::this_thread::sleep_for(std::chrono::milliseconds(250));
    worker.request_stop();
} // jthread joins here: no detach, no manual join, no forgotten thread

Observed output (with the gcc16 lib path at runtime):

stopped cleanly

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.