C++20的std::jthread是什么_C++支持自动汇合与中断的线程类

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(),只要线程处于可汇合状态,就能安全等待其结束,无需开发者显式处理。

  • 不再需要担心忘记 join 导致程序终止
  • 作用域结束时线程自动汇合,资源管理更可靠

支持协作式中断:优雅停止线程

std::jthread 内建了中断机制,通过 std::stop_tokenstd::stop_source 实现协作式中断。线程可以定期检查是否收到中断请求,并自行决定如何退出。

每个 jthread 对象自带一个 std::stop_source,可通过 get_stop_source() 获取,也可将 std::stop_token 传递给任务函数,用于监听中断。

  • 调用 request_stop() 发起中断请求
  • 线程函数中通过 stop_token.stop_requested() 检查是否应退出
  • 支持在条件变量上使用 wait(std::stop_token),被唤醒时自动检测中断

使用示例:简洁又安全

下面是一个简单的 std::jthread 使用例子:

#include 
#include 
#include 

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 多线程编程的推荐选择。不复杂但容易忽略的是协作式中断的设计理念:不强制终止,而是通知退出。