std::jthread是C++20中可自动合并的线程类,其析构函数会自动调用join()避免程序终止,并支持通过stop_token和request_stop()实现协作式中断,提升线程管理的安全性与便捷性。

在C++20中,std::jthread 是对 std::thread 的改进版本,提供了更安全、更便捷的线程管理方式。它最大的特点是支持自动线程合并(join)和协作式中断(cooperative interruption),避免了因忘记调用 join() 而导致程序终止的问题。
什么是 std::jthread?
std::jthread 是 "joining thread" 的缩写,它的析构函数会自动调用 join(),确保线程正确结束,不会像 std::thread 那样在未 join 时触发 std::terminate()。
此外,它内置了停止机制,通过 std::stop_token 和 std::stop_source 实现线程的协作式中断,让线程可以安全地响应外部停止请求。
基本用法:替代 std::thread
使用 std::jthread 启动一个线程非常简单,语法与 std::thread 几乎一致:
立即学习“C++免费学习笔记(深入)”;
#include
#include
#include
void task() {
for (int i = 0; i < 5; ++i) {
std::cout << "Working... " << i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
int main() {
std::jthread t(task); // 自动管理,无需手动 join
// 析构时会自动 join
return 0;
}
上面的例子中,main 函数结束时,t 被销毁,其析构函数会自动等待线程执行完毕,无需手动调用 join()。
协作式中断:安全停止线程
std::jthread 支持通过 stop_token 检查是否收到停止请求,并主动退出。这是 C++20 新增的重要特性。
示例:响应中断请求
#include
#include
#include
void cancellable_task(std::stop_token stoken) {
for (int i = 0; i < 10; ++i) {
if (stoken.stop_requested()) {
std::cout << "任务被取消,正在退出...\n";
return;
}
std::cout << "工作 " << i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
std::cout << "任务完成。\n";
}
int main() {
std::jthread t(cancellable_task);
std::this_thread::sleep_for(std::chrono::milliseconds(1200));
t.request_stop(); // 请求线程停止
return 0;
}
在这个例子中:
- cancellable_task 接收一个 std::stop_token 参数
- 循环中定期检查 stop_requested()
- 主线程在 1.2 秒后调用 request_stop() 发出中断信号
- 子线程检测到后优雅退出
获取 stop_token 和自定义逻辑
你也可以在任务内部获取 jthread 的 stop_token:
void task_with_internal_check(std::jthread& t) {
auto token = t.get_stop_token();
for (int i = 0; i < 100; ++i) {
if (token.stop_requested()) {
std::cout << "收到停止信号\n";
return;
}
std::cout << "第 " << i << " 次运行\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
注意参数是引用,避免拷贝 jthread。
基本上就这些。std::jthread 让多线程编程更安全、更简洁,特别是自动 join 和中断机制,减少了资源泄漏和死锁风险。如果你使用 C++20 或更高版本,推荐优先使用 std::jthread 替代 std::thread。








