std::jthread 与自动 join
什么是 std::jthread
std::jthread 是 C++20 引入的线程类,定义在 <thread> 头文件中。它是 std::thread 的改进版本,主要有两个增强:
- 自动 join:析构时自动调用
join(),不会像std::thread那样因为忘记 join 而调用std::terminate() - 协作取消:内置
std::stop_source,支持通过std::stop_token请求线程停止
#include <thread>
void worker() { /* 工作 */ }
// std::thread:必须手动 join,否则析构时程序终止
// std::jthread:析构时自动 join,安全
{
std::jthread jt(worker); // 离开作用域时自动 join
}jthread vs thread
| 特性 | std::jthread | std::thread |
|---|---|---|
| 析构行为 | 自动 request_stop + join | 调用 std::terminate |
| 协作取消 | 内置 stop_source/stop_token | 需要手动实现 |
| 异常安全 | RAII 保证 | 需要 try-catch 或 scope guard |
| 可移动 | 是 | 是 |
| 可复制 | 否 | 否 |
| 头文件 | <thread> | <thread> |
基本示例
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <mutex>
#include <string>
std::mutex cout_mutex; // 保护 cout 的互斥量
// 线程安全的打印函数
void safe_print(const std::string& msg) {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << msg << std::endl;
}
// ============================
// 示例1:自动 join 的基本行为
// ============================
void auto_join_demo() {
safe_print("--- 创建 jthread ---");
{
std::jthread jt([] {
safe_print(" 线程开始工作");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
safe_print(" 线程工作完成");
});
safe_print(" 主线程继续执行...");
// jt 在这里析构,自动调用 join()
// 主线程会等待工作线程完成
}
safe_print("--- jthread 已析构(已自动 join)---");
}
// ============================
// 示例2:对比 thread 的危险性
// ============================
void thread_danger_demo() {
// std::thread 版本(危险)
// 如果忘记 join 或 detach,析构时会调用 std::terminate()
/*
{
std::thread t([] { /* 工作 */ });
// 如果这里抛出异常,t 没有被 join
// t.~thread() 会调用 std::terminate()
}
*/
// std::jthread 版本(安全)
{
std::jthread jt([] {
safe_print(" jthread 工作中...");
});
// 即使这里抛出异常,jt 的析构函数也会安全地 join
}
safe_print(" jthread 安全退出");
}
// ============================
// 示例3:带 stop_token 的协作取消
// ============================
void stop_token_demo() {
// 如果线程函数的第一个参数是 stop_token,jthread 会自动传入
std::jthread jt([](std::stop_token stoken) {
int counter = 0;
while (!stoken.stop_requested()) {
counter++;
safe_print(" 工作中... 计数: " + std::to_string(counter));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
safe_print(" 收到停止请求,退出(计数: " + std::to_string(counter) + ")");
});
// 主线程等待一段时间
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// 手动请求停止
jt.request_stop();
safe_print("已发送停止请求");
// jt 析构时会 join,等待线程响应停止请求并退出
}
// ============================
// 示例4:带参数的线程函数
// ============================
void params_demo() {
// 带额外参数(stop_token 之后的参数)
std::jthread jt([](std::stop_token stoken, int id, const std::string& name) {
safe_print(" 线程 " + std::to_string(id) + " (" + name + ") 启动");
while (!stoken.stop_requested()) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
safe_print(" 线程 " + std::to_string(id) + " (" + name + ") 停止");
}, 1, "工作线程");
std::this_thread::sleep_for(std::chrono::milliseconds(150));
// 析构时自动 request_stop + join
}
// ============================
// 示例5:多个 jthread
// ============================
void multi_thread_demo() {
std::vector<std::jthread> threads;
// 创建多个线程
for (int i = 0; i < 5; i++) {
threads.emplace_back([](std::stop_token stoken, int id) {
safe_print(" 线程 " + std::to_string(id) + " 启动");
while (!stoken.stop_requested()) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
safe_print(" 线程 " + std::to_string(id) + " 退出");
}, i);
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// vector 销毁时,所有 jthread 自动 request_stop + join
safe_print("销毁线程集合...");
}
// ============================
// 示例6:get_stop_source 和 get_stop_token
// ============================
void stop_source_demo() {
std::jthread jt([](std::stop_token stoken) {
while (!stoken.stop_requested()) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
safe_print(" 线程已停止");
});
// 获取 stop_source——可以在外部请求停止
std::stop_source ss = jt.get_stop_source();
// 获取 stop_token——可以查询是否已请求停止
std::stop_token st = jt.get_stop_token();
safe_print("stop_requested: " + std::string(st.stop_requested() ? "true" : "false"));
// 通过 stop_source 请求停止
ss.request_stop();
safe_print("stop_requested: " + std::string(st.stop_requested() ? "true" : "false"));
}
// ============================
// 示例7:jthread 的移动语义
// ============================
void move_demo() {
std::jthread jt1([] {
safe_print(" 线程工作中...");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
});
safe_print("jt1 joinable: " + std::string(jt1.joinable() ? "true" : "false"));
// 移动 jthread(转移所有权)
std::jthread jt2 = std::move(jt1);
safe_print("移动后 jt1 joinable: " + std::string(jt1.joinable() ? "true" : "false"));
safe_print("移动后 jt2 joinable: " + std::string(jt2.joinable() ? "true" : "false"));
// jt2 析构时自动 join
}
// ============================
// 示例8:析构时的行为细节
// ============================
void destructor_detail_demo() {
// jthread 析构函数的伪代码:
// ~jthread() {
// if (joinable()) {
// request_stop(); // 先请求停止
// join(); // 再等待结束
// }
// }
std::jthread jt([](std::stop_token stoken) {
safe_print(" 线程开始");
// 模拟长时间工作,但会检查停止请求
for (int i = 0; i < 100 && !stoken.stop_requested(); i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
safe_print(" 线程结束");
});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
safe_print("即将析构 jthread...");
// 析构时:先 request_stop(),线程检测到后退出循环,然后 join() 返回
}
int main() {
std::cout << "=== 自动 join ===" << std::endl;
auto_join_demo();
std::cout << "\n=== 安全性 ===" << std::endl;
thread_danger_demo();
std::cout << "\n=== stop_token ===" << std::endl;
stop_token_demo();
std::cout << "\n=== 带参数 ===" << std::endl;
params_demo();
std::cout << "\n=== 多线程 ===" << std::endl;
multi_thread_demo();
std::cout << "\n=== stop_source ===" << std::endl;
stop_source_demo();
std::cout << "\n=== 移动语义 ===" << std::endl;
move_demo();
std::cout << "\n=== 析构细节 ===" << std::endl;
destructor_detail_demo();
return 0;
}jthread 的析构流程
jthread::~jthread() {
if (joinable()) {
request_stop(); // 1. 先通知线程停止
join(); // 2. 再等待线程退出
}
}这意味着如果线程函数不检查 stop_token,析构时的 join() 会一直阻塞直到线程自然结束。所以长时间运行的线程应该定期检查 stop_requested()。
适用场景
- 替代 std::thread 获得异常安全的线程管理
- 需要协作取消的后台工作线程
- RAII 风格的线程生命周期管理
- 管理多个线程的容器(vector<jthread>)
- 周期性任务(循环中检查 stop_token)
常见问题
jthread 可以 detach 吗?
从 C++20 标准来看,jthread 不提供 detach() 方法。如果需要 detach 语义,应该使用 std::thread。
如果线程函数不接受 stop_token 会怎样?
jthread 仍然可以使用——它不要求线程函数必须接受 stop_token。但这样析构时 request_stop() 就没有效果,join() 会等到线程自然结束。
jthread 的 request_stop() 是线程安全的吗?
是的。request_stop() 可以从任何线程安全地调用,内部使用原子操作。
多次调用 request_stop() 会怎样?
安全的。第一次调用后 stop_requested() 变为 true,后续调用没有额外效果。
注意事项
- jthread 析构时自动 request_stop + join
- 长时间运行的线程应该检查 stop_requested()
- 如果不检查 stop_token,析构时会阻塞直到线程自然结束
- jthread 是 move-only 的,不能复制
- jthread 没有 detach() 方法
- stop_token 作为线程函数的第一个参数时会自动传入
总结
std::jthread 是 C++20 对 std::thread 的重大改进。自动 join 的 RAII 语义消除了忘记 join 导致程序终止的风险,让线程管理变得异常安全。内置的 stop_source/stop_token 机制提供了标准化的协作取消,线程函数可以通过检查 stop_requested() 来响应停止请求。析构时 jthread 会先 request_stop() 再 join(),确保线程有机会优雅退出。对于新的 C++20 项目,应该优先使用 std::jthread 而不是 std::thread。