std::thread与std::jthread(C++20)的使用与区别
请说明std::thread的创建、join/detach用法,线程RAII管理(如使用std::jthread),以及C++20 std::jthread相比std::thread增加的自动join和停止令牌(stop_token)机制。
回答
屠龙少年
std::thread(C++11):
- 创建:
std::thread t(func, args...),立即开始执行。 t.join():阻塞等待线程结束(必须调用,否则析构时std::terminate)。t.detach():分离线程,后台运行(访问局部变量可能悬空)。- 不可拷贝,可移动。
RAII管理:
class ThreadGuard {
std::thread& t;
public:
explicit ThreadGuard(std::thread& t_) : t(t_) {}
~ThreadGuard() { if (t.joinable()) t.join(); }
};
std::jthread(C++20):
- 析构时自动join(若joinable),减少遗忘join的错误。
- 内置
std::stop_source/std::stop_token停止机制。
std::jthread jt([](std::stop_token st) {
while (!st.stop_requested()) {
// 处理任务
}
});
// jt析构时自动请求停止并join
jt.request_stop(); // 显式请求停止
区别总结: | 特性 | std::thread | std::jthread | |------|------------|-------------| | 自动join | 否(需手动) | 是(析构时) | | 停止机制 | 无 | 内建stop_token | | 可替换性 | 基础 | 推荐替代thread |
注意:jthread在析构时不能被Join为可等待,若需分离行为仍需detach。