

新闻资讯
技术学院std::jthread是C++20引入的增强型线程类,核心特性为析构时自动join()保障RAII安全,并原生支持协作式中断(通过stop_token和request_stop())。
std::jthread 是 C++20 引入的线程类,全称是 joining thread,本质是 std::thread 的增强版,核心改进两点:自动 join()(RAII 安全) + 原生支持线程可中断(cooperative interruption)。
传统 std::thread 对象析构前必须明确处于 joinable() 状态,否则会调用 std::terminate(),容易出错。而 std::jthread 在析构时自动执行 join(),确保资源安全回收。
例如:
void worker() { std::this_thread::sleep_for(1s); }std::jthread 构造时可接收一个带 std::stop_token 参数的可调用对象,运行时可通过 request_stop() 主动通知线程退出,线程内部用 stop_token 检查是否被请求中断。
关键点:
std::condition_variable::wait、std::this_thread::sleep_for 等)std::stop_token 可传给 std::condition_variable::wait,使其在收到中断请求时提前唤醒并抛出 std::stop_exception(可捕获)std::jthread 只能请求一次中断;多次 request_stop() 无副作用典型用法结构:
void worker(std::stop_tok
en stoken) {std::jthread 并非替代,而是补充。它不提供 detach(),也不允许移动后仍保持 joinable(移动后原对象变为不可 join 状态)。若需 detach 行为,仍用 std::thread;若追求安全和可中断,优先选 std::jthread。
它还提供了 get_stop_source() 和 get_stop_token(),方便在线程内外传递停止信号,支持更灵活的取消传播。
基本上就这些 —— std::jthread 让多线程代码更简洁、更安全、更易控制,尤其适合需要优雅退出的长期运行任务。