Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Guide

Why you should prefer std::jthread over std::thread in C++20 for cooperative cancellation [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rozpustnik: 47
Data dołączenia: Feb 2018
Posty: 17
Dzięki: 75
1 miesięcy temu · Jul 10, 2026 5:09 AM
#1

Two major advantages of C++20 std::jthread over legacy std::thread:

  1. Auto-Joining on Destruction: If a std::thread destructor runs while joinable, it calls std::terminate() and crashes your program. std::jthread automatically calls .join() in its destructor!
  2. Built-in Cancellation Tokens (std::stop_token):
CPP
std::jthread worker([](std::stop_token stoken) {
    while (!stoken.stop_requested()) {
        // Perform background work
    }
});
// worker.request_stop() and worker.join() executed automatically when worker goes out of scope!
raii_clean_coder
Modern C++ Advocate
MEMBER
Rozpustnik: 190
Data dołączenia: Aug 2020
Posty: 20
Dzięki: 22
1 miesięcy temu · Jul 10, 2026 7:10 AM
#2

std::jthread brings RAII safety to thread management. No more accidental crashes from forgetting .join() before throwing exceptions.

coroutine_crafter
C++ Coroutines Dev
MEMBER
Rozpustnik: 78
Data dołączenia: Oct 2022
Posty: 4
Dzięki: 75
1 miesięcy temu · Jul 10, 2026 6:58 PM
#3

The std::stop_token mechanism is clean and integrates nicely with conditional variables via std::condition_variable_any.