std::jthread在C++20中引入,具备自动汇合与协作式中断功能。析构时自动join避免资源泄漏,集成stop_token机制支持安全线程终止,提升多线程编程的安全性与便捷性。

std::jthread 是 C++20 引入的一个新线程类,它是对 std::thread 的改进和封装,主要增加了两项关键功能:自动汇合(automatic joining)和线程中断支持(cooperative interruption)。这让多线程编程更安全、更便捷。
在 C++11 中使用 std::thread 时,必须手动调用 join() 或 detach(),否则程序在析构未汇合的线程时会调用 std::terminate(),导致崩溃。
std::jthread 在析构函数中会自动调用 join(),只要线程处于可汇合状态,就能安全等待其结束,无需开发者显式处理。
std::jthread 内建了中断机制,通过 std::stop_token 和 std::stop_source 实现协作式中断。线程可以定期检查是否收到中断请求,并自行决定如何退出。
立即学习“C++免费学习笔记(深入)”;
每个 jthread 对象自带一个 std::stop_source,可通过 get_stop_source() 获取,也可将 std::stop_token 传递给任务函数,用于监听中断。
下面是一个简单的 std::jthread 使用例子:
#include <thread>
#include <iostream>
#include <chrono>
void worker(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(500));
}
}
int main() {
std::jthread t(worker); // 自动传入 stop_token
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
t.request_stop(); // 请求中断
// 析构时自动 join,无需手动操作
return 0;
}
基本上就这些 —— std::jthread 让线程管理变得更现代、更安全,减少常见错误,是 C++20 多线程编程的推荐选择。不复杂但容易忽略的是协作式中断的设计理念:不强制终止,而是通知退出。
以上就是C++20的std::jthread是什么_C++支持自动汇合与中断的线程类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号