【C++】std::jthread
std::jthread
1. 自动 join
std::jthread在析构时会自动调用join()。- 不再需要手动
join()或detach(),避免了资源泄露或程序崩溃。
2. 支持取消(stop_token)
std::jthread可以配合stop_token实现线程的 协作式中断,这是现代线程取消机制的重要进步。
#include <iostream>
#include <thread>
void work() {
std::cout << "工作线程 id: " << std::this_thread::get_id() << "\n";
}
int main() {
std::jthread t(work); // 自动 join
std::cout << "主线程 id: " << std::this_thread::get_id() << "\n";
}
#include <iostream>
#include <thread>
#include <chrono>
void task(std::stop_token stoken) {
while (!stoken.stop_requested()) {
std::cout << "工作中...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "停止请求已收到,退出线程。\n";
}
int main() {
std::jthread t(task); // jthread 自动传入 stop_token
std::this_thread::sleep_for(std::chrono::seconds(2));
t.request_stop(); // 发出取消请求
}

浙公网安备 33010602011771号