跳到主要内容
版本:1.0

jthread

std::jthread 是 C++20 对 std::thread 的改进版,两个核心升级:析构时自动 join(不再 std::terminate),以及内置 stop_token 实现协作式线程取消。

头文件与基本特征

#include <thread>
特征std::threadstd::jthread (C++20)
自动 join❌ 忘记 join/detach 则 terminate✅ 析构自动 join
协作取消❌ 需自行实现✅ 内置 stop_token
移动语义可移动可移动

基本用法

#include <iostream>
#include <thread>

int main() {
std::jthread t([] {
std::cout << "hello from jthread\n";
});
// 不用写 join(),析构自动 join
return 0;
}

jthread 消除了 C++11 最大的坑之一:忘记 join/detach 导致的 std::terminate

协作取消:stop_token

jthread 构造时自动关联一个 stop_source,线程函数可接收 std::stop_token 检查是否被请求停止:

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

int main() {
std::jthread worker([](std::stop_token stoken) {
while (!stoken.stop_requested()) {
std::cout << "working...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "cancelled\n";
});

std::this_thread::sleep_for(std::chrono::milliseconds(300));

// 请求取消(或析构时自动做)
worker.request_stop();
worker.join();

return 0;
}

关键点:

  1. request_stop() 给线程发信号"请停止"。
  2. 线程函数通过 stoken.stop_requested() 轮询,自己决定何时退出。
  3. 这是协作式取消——不是强杀线程,而是给线程一个退出信号。

常用接口

接口作用
request_stop()请求取消当前线程
get_stop_source()获取关联的 stop_source
get_stop_token()获取外部可用的 stop_token
joinable() / join()std::thread
get_id() / hardware_concurrency()std::thread

使用注意

  1. jthread 析构会 join(),所以程序退出前能自动等待线程完成。
  2. 如果需要 detach(),仍然可以用,但要手动调用。
  3. request_stop() 只是请求,线程可以不响应——你需要在线程代码里检查 stop_requested()
  4. 如果不需要 stop 机制,传普通函数(不带 stop_token 参数)即可。

小结

std::jthread = std::thread + RAII + 协作取消。C++20 起,新代码中创建线程应默认使用 jthread 而不是 thread