Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
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
مندوب: 47
تاريخ الانضمام: Feb 2018
دعامات: 17
شكرًا: 75
1 months ago · 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
مندوب: 190
تاريخ الانضمام: Aug 2020
دعامات: 20
شكرًا: 22
1 months ago · 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
مندوب: 78
تاريخ الانضمام: Oct 2022
دعامات: 4
شكرًا: 75
1 months ago · 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.