c++ jthread 使用详解

c++ jthread 使用详解

std::jthread c++20

  • 头文件 #include <thread>
  • 对 std::thread 的改进,旨在提供更好的线程管理和异常处理,除了拥有和 std::thread 完全相同的功能以及 API 之外,还增加了以下功能:
    • 可停止:提供了停止线程相关的 API,可以更好的管理线程;
    • 顶层函数:jthread 所要运行的顶层函数可选的接收一个 std::stop_token 对象作为第一个参数;
    • 自动停止:析构函数会调用 request_stop 方法,停止当前线程;
    • 自动加入:析构函数会根据当前线程的 joinable 状态,自动调用 join 方法,不再需要显式调用 join 来等待线程结束,从而避免了忘记加入线程带来的问题;
    • 异常处理:jthread 对象可以处理线程中可能抛出的异常,确保异常不会无限制地传播到主线程之外;

停止相关 API

  • get_stop_source:返回与线程的停止状态关联的 stop_source 对象,一般用于停止线程;
  • get_stop_token:返回与线程的共享停止状态关联的 stop_token,一般用于查询线程停止状态;
  • request_stop:请求线程停止;

基本使用

#include <chrono>
#include <thread>

using namespace std::literals;

void f(int n)
{
    for (int i = 0; i < 5; ++i) {
        printf("thread is running\n");
        ++n;
        std::this_thread::sleep_for(10ms);
    }
    printf("n is %d\n", n);
}

int main()
{
    int n = 0;
    std::jthread t(f, n + 1);
    // t 在析构时结合
}

停止使用

#include <thread>
#include <chrono>

using namespace std::literals;

void f(std::stop_token stoken, int n) {
    while (!stoken.stop_requested()) {
        printf("thread is running\n");
        ++n;
        std::this_thread::sleep_for(10ms);
    }
    printf("thread is stop, n is %d\n", n);
}

int main() {
    int n = 0;
    std::jthread t(f, n);
    std::this_thread::sleep_for(50ms);

    auto st = t.get_stop_token();
    // 查询是否可停止
    printf("main, thead can stop %d\n", st.stop_possible());

    // 停止线程第一种方法
    t.request_stop();

    // 停止线程第二种方法
    // auto src = t.get_stop_source();
    // src.request_stop();

    // 查询是否已被请求停止
    printf("main, thead is requested stop %d\n", st.stop_requested());

    // t 在析构时自动停止并结合
    return 0;
}
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注的罗哈哈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值