详解"/>
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 使用详解
发布评论