在C++20之前,我们一般用std::thread创建线程,但必须记住在销毁前调用join或者detach,否则程序会直接终止。C++20新增的std::jthread是一个能自动管理线程生命周期的线程类,它在析构时会自动调用join,并且原生支持通过stop_token发出停止请求,让线程可以协作式退出。

std::jthread 和普通 std::thread 的区别
最核心的区别有两点:第一,jthread在离开作用域时自动join,不容易写出漏join的bug;第二,jthread的线程函数可以接收一个std::stop_token参数,用来响应外部的中断请求。
| 特性 | std::thread | std::jthread |
|---|---|---|
| 析构行为 | 未join或detach则terminate | 自动join |
| 中断支持 | 无 | 内置stop_token |
| 获取停止状态 | 不支持 | 支持stop_source和stop_token |
基本用法示例
下面代码展示如何使用std::jthread启动一个后台任务,并在作用域结束时自动回收线程。
#include <iostream>
#include <thread>
#include <chrono>
void worker(std::stop_token st) {
while (!st.stop_requested()) {
std::cout << "工作中..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "收到停止请求,退出" << std::endl;
}
int main() {
std::jthread t(worker); // 自动管理生命周期
std::this_thread::sleep_for(std::chrono::seconds(2));
// 离开main作用域时,t析构自动join,并通过stop_token请求停止
return 0;
}
手动请求停止线程
除了析构时自动停止,我们也可以拿到jthread内部的stop_source主动发停止信号。
#include <iostream>
#include <thread>
#include <chrono>
void task(std::stop_token st) {
while (!st.stop_requested()) {
std::cout << "运行" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
}
int main() {
std::jthread jt(task);
std::this_thread::sleep_for(std::chrono::seconds(1));
jt.request_stop(); // 主动请求停止
// 析构时自动join
}
使用注意事项
- jthread需要编译器支持C++20,例如GCC 10以上、Clang 11以上。
- 线程函数第一个参数如果是std::stop_token,jthread会自动传入,不要自己构造。
- 如果线程函数不支持stop_token,jthread也能像普通thread一样运行,只是没有中断能力。
总结
std::jthread是C++20给并发编程带来的实用改进,它把线程回收和中断控制标准化了。用jthread写出来的代码更短也更安全,建议在新项目里优先替代std::thread。
std::jthreadC++20线程生命周期自动 joinstop_token修改时间:2026-07-25 01:18:18