c++ jthread 使用详解

编程入门 行业动态 更新时间:2024-10-19 02:17:24

c++ jthread 使用<a href=https://www.elefans.com/category/jswz/34/1770044.html style=详解"/>

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;
}

更多推荐

c++ jthread 使用详解

本文发布于:2023-11-14 14:30:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587681.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:详解   jthread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!