c++20中的jthread再谈

news/发布时间2024/7/27 11:16:11

一、介绍

在前面的C++20新功能中,简单的介绍过相关的std::jthread的应用。当时觉得它虽然比std::thread方便一些,但也没有多大的优势。可在后面的不断的学习中,发现std::jthread的使用上确实有优秀之处,相对于传统的线程编程,等于是提前安全的封装了对线程安全管理和控制的相关模块和接口。

二、std::jthread应用

一般来说对线程的应用主要有以下几类:
1、线程管理
线程管理,就是对线程的按需启动和安全退出有一个最基础的要求,在std::thread中可以通过线程分离和Join来控制线程的安全退出,使用一些变量来处理线程中循环的退出。但这些在std::jthread中都有了安全的应用机制:
线程启动:直接启动即可。
线程退出处理:自动合并joining,这个没什么可说的。
线程停止控制:线程取消使用std::stop_token和std::stop_source。std::stop_source负责维护线程的共享停止状态,提供了一种发出停止线程的请求方法。它可以与std::stop_token与std::stop_callback共同工作。std::stop_token可以理解成一种对线程退出状态的查看(查看关联的std::stop_source),如果满足条件就退出。
其实线程的启动还相对好控制一些,特别是线程的退出,一般对初学者来说,都是比较难以驾驭的,经常是线程退出整个程序也崩溃了。所以std::jthread提供的这个退出控制还是不错的。

2、条件变量
在多线程编程中,Linux环境下使用条件变量的很多,但在C++20中配合std::condition_variable_any,则会更加方便。std::condition_variable_any比std::condition_variable应用更广泛,而不只是局限于对 std::unique_lockstd::mutex的控制,意味着能支持更多的锁机制。

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>void testConditionAny(std::stop_token sToken) {std::mutex mutex;std::unique_lock lock(mutex);// cv_any::wait内部含std::stop_token的重载,当sToken停止会调用cv_any的唤醒动作std::condition_variable_any().wait(lock, sToken, [] {//这个谓词类似于处理假唤醒的bool值return false;});std::cout << "jthread function testConditionAny quit!" << std::endl;
}
int main() {//jthread的RAII封装会调用request_stop()std::jthread testAny(testConditionAny);std::this_thread::sleep_for(std::chrono::seconds(1));return 0;
}

其实这个和普通的condition_variable的用法是一致的。

3、回调处理
如果说上面的“条件变量”和std::jthread没有必然联系,但在线程中的回调还是相当重要的。在C++20中针对std::jthread则提供了一个回调std::stop_callback类。这个有一个细节需要注意,如果是此回调执行了,则在关联的 std::stop_token 的std::stop_source 调用了 request_stop() 的同一线程中调用。否则在构造的线程中执行。

三、例程

先看一个stop_source的例程:

#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>using namespace std::chrono_literals;void worker_fun(int id, std::stop_source stop_source)
{std::stop_token stoken = stop_source.get_token();for (int i = 10; i; --i){std::this_thread::sleep_for(300ms);if (stoken.stop_requested()){std::printf("  工作线程%d 被请求停止\n", id);return;}std::printf("  工作线程%d 返回睡眠\n", id);}
}int main()
{std::jthread threads[4];std::cout << std::boolalpha;auto print = [](const std::stop_source& source){std::printf("stop_source stop_possible = %s, stop_requested = %s\n",source.stop_possible() ? "true" : "false",source.stop_requested() ? "true" : "false");};// 普通停止信号源std::stop_source stop_source;print(stop_source);// 创建工作线程for (int i = 0; i < 4; ++i)threads[i] = std::jthread(worker_fun, i + 1, stop_source);std::this_thread::sleep_for(500ms);std::puts("请求停止");stop_source.request_stop();print(stop_source);// 注意:jthreads 的析构函数会调用 join,因此无需显式调用
}

运行结果:

stop_source stop_possible = true, stop_requested = false工作线程2 返回睡眠工作线程3 返回睡眠工作线程1 返回睡眠工作线程4 返回睡眠
请求停止
stop_source stop_possible = true, stop_requested = true工作线程3 被请求停止工作线程1 被请求停止工作线程2 被请求停止工作线程4 被请求停止

再看一个回调函数的:

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>using namespace std::chrono_literals;// 使用一个辅助类进行原子 std::cout 流输出。
class Writer {std::ostringstream buffer;public:~Writer() { std::cout << buffer.str(); }Writer &operator<<(auto input) {buffer << input;return *this;}
};int main() {// 工作线程。// 它将等待直至被请求停止。std::jthread worker([](std::stop_token stoken) {Writer() << "工作线程 id: " << std::this_thread::get_id() << '\n';std::mutex mutex;std::unique_lock lock(mutex);std::condition_variable_any().wait(lock, stoken, [&stoken] { return stoken.stop_requested(); });});// 在工作线程上注册停止回调。std::stop_callback callback(worker.get_stop_token(),[] { Writer() << "执行了停止回调,线程: " << std::this_thread::get_id() << '\n'; });// 可以提前销毁 stop_callback 对象以阻止其执行。{std::stop_callback scoped_callback(worker.get_stop_token(), [] {// 这里不会执行。Writer() << "作用域内的停止回调被执行,线程: " << std::this_thread::get_id() << '\n';});}// 演示由哪个线程何时执行 stop_callback。// 定义停止函数。auto stopper_func = [&worker] {std::cout << std::this_thread::get_id() << '\n';if (worker.request_stop())Writer() << "执行了停止请求,线程: " << std::this_thread::get_id() << '\n';elseWriter() << "未执行停止请求,线程: " << std::this_thread::get_id() << '\n';};// 使多个线程竞争以停止工作线程。std::jthread stopper1(stopper_func);std::jthread stopper2(stopper_func);stopper1.join();stopper2.join();// 已经请求停止后,立即执行新的 stop_callback。Writer() << "主线程: " << std::this_thread::get_id() << '\n';std::stop_callback callback_after_stop(worker.get_stop_token(), [] { Writer() << "执行了停止回调,线程: " << std::this_thread::get_id() << '\n'; });
}

执行结果:

工作线程 id: 140149702784576
140149694391872
140149685999168
执行了停止回调,线程: 140149694391872
执行了停止请求,线程: 140149694391872
未执行停止请求,线程: 140149685999168
主线程: 140149709902784
执行了停止回调,线程: 140149709902784

需要知道的是,stop_token 的获取可以从stop_source得到也可以从std::jthread得到,都有相关的获取API接口。
注:代码来自cppreference

四、总结

目前很少听说在实际工程中有应用jthread的,可能大家觉得thread就比较好用,也可能是开发习惯和代码惯性的问题。std::jthread需要支持的版本也比较高得到c++20,估计这也是一个非常重要的原因。毕竟,现在C++11都没有真正普及开来,很多开发者仍然只是使用一些非常简单的新特性。
还是要追上来,与是俱进!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.shwantai.cn/a/50100635.html

如若内容造成侵权/违法违规/事实不符,请联系万泰站长网进行投诉反馈email:xxxxxxxx@qq.com,一经查实,立即删除!

相关文章

苹果手表Apple Watch录了两个半小时的录音,却只能播放4秒,同步到手机也一样,还能修复好吗?

好多人遇到这个情况&#xff0c;用苹果手表Apple Watch录音&#xff0c;有的录1个多小时&#xff0c;有的录了3、4小时&#xff0c;甚至更长时间&#xff0c;因为手表没电&#xff0c;忘记保存等原因造成录音损坏&#xff0c;都是只能播放4秒&#xff0c;同步到手机也一样&…

v-text 和v-html

接下来&#xff0c;我讲介绍一下v-text和v-html的使用方式以及它们之间的区别。 使用方法 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta name"viewport" content"widthdevice-widt…

C++核心编程——4.2(2)对象的初始化和清理

4.2.5 深拷贝与浅拷贝 浅拷贝&#xff1a;编译器提供的简单的赋值拷贝操作 深拷贝&#xff1a;在堆区重新申请空间&#xff0c;进行拷贝操作 示例&#xff1a; class Person { public://无参&#xff08;默认&#xff09;构造函数Person() {cout << "无参构造函数…

韩顺平 | 零基础快速学Python

环境准备 开发工具&#xff1a;IDLE、Pycharm、Sublime Text、Eric 、文本编辑器&#xff08;记事本/editplus/notepad&#xff09; Python特点&#xff1a;既支持面向过程OOP、也支持面向对象编程&#xff1b;具有解释性&#xff0c;不需要编程二进制代码&#xff0c;可以直…

Rust---复合数据类型之枚举、数组

目录 枚举的使用Option 枚举数组的使用输出结果 枚举&#xff08;Enum&#xff09;&#xff1a;表示一个类型可以有多个不同的取值。枚举类型可以包含不同的变体&#xff08;variants&#xff09;&#xff0c;每个变体可以有不同的数据类型。 枚举的使用 enum Direction {Up,…

Windows下Docker搭建Flink集群

编写docker-compose.yml 参照&#xff1a;https://github.com/docker-flink/examples/blob/master/docker-compose.yml version: "2.1" services:jobmanager:image: flink:1.14.4-scala_2.11expose:- "6123"ports:- "18081:8081"command: jobma…