Boost中线程的使用

目录

boost的线程基本用法

boost:condition

thread_group 线程组

thread_pool


boost的线程基本用法

boost::thread Thread_GenerateUuid;boost::thread Thread_ShowUuid;boost::mutex mutex;std::queue<std::string>UuidQueue;void procGenerateUuid();void showUuid();void GetPveDataDemo::procGenerateUuid()
{try{for (;;){boost::this_thread::sleep_for(boost::chrono::seconds(2));boost::this_thread::interruption_point(); // 手动在线程中加入中断点,中断点不影响其他语句执行 当其他地方触发该断点(thread.interrupt())再次执行到此处,抛出boost::thread_interrupted异常,若未捕捉则线程终止。 if (UuidQueue.size() <= 5){boost::lock_guard<boost::mutex> lck_guard(mutex);std::string uuid = QUuid::createUuid().toString().toStdString();UuidQueue.push(uuid);}}}catch (...){}
}void GetPveDataDemo::showUuid()
{try{int cnt = 1;for (;;){boost::this_thread::sleep_for(boost::chrono::seconds(2));boost::this_thread::interruption_point();// 手动在线程中加入中断点,中断点不影响其他语句执行 当其他地方触发该断点可从该循环中退出if (!UuidQueue.empty()){boost::lock_guard<boost::mutex> lck_guard(mutex);std::string cuuid = UuidQueue.front();UuidQueue.pop();QString UuidDisplay = "#:" + QString::number(cnt) + ": " + QString(cuuid.c_str()) + "\n";ui.textBrowser_UUID->append(UuidDisplay);//界面和线程写在一起了不太好	++cnt;}}}catch (...){}
}void GetPveDataDemo::on_pushButton_2_clicked()
{//Uuid线程if (!Thread_GenerateUuid.joinable() && !Thread_ShowUuid.joinable())	//joinable判断线程是否结束{Thread_GenerateUuid = boost::thread(boost::bind(&GetPveDataDemo::procGenerateUuid, this));Thread_ShowUuid = boost::move(boost::thread(boost::bind(&GetPveDataDemo::showUuid, this)));ui.pushButton_2->setText(QString::fromLocal8Bit("停止生成UUID"));}else{Thread_GenerateUuid.interrupt(); //向线程发送中断请求Thread_ShowUuid.interrupt();Thread_GenerateUuid.join();//join连接 detach是脱离线程 不会阻塞Thread_ShowUuid.join();	 //join函数,作用是等待直到线程执行结束; 阻塞当前线程ui.pushButton_2->setText(QString::fromLocal8Bit("开始生成UUID"));ui.textBrowser_UUID->clear();ui.textBrowser_UUID->append(QString::fromLocal8Bit("当前生产线程停止"));ui.textBrowser_UUID->append(QString::fromLocal8Bit("当前消费线程停止"));}//move 移动语义 将临时对象的所有权给予GenerateUuid,避免临时变量不必要的拷贝和析构
}

boost:condition

与std的条件变量一样会有虚假唤醒问题,同样需要谓词处理。

#define LANENUM 32boost::mutex mtx_etcSignal[LANENUM];
boost::condition m_cond_etcSignal[LANENUM];map<string,int> plateNo2flag;bool waitForEtcSignal(int laneNo,const string&plate,int connTime)
{boost::mutex::scoped_lock lk(mutex mtx_etcSignal[laneNo]);m_cond_etcSignal[laneNo].wait_for(lk,bost::chrono::milliseconds(connTime),[&](){if(plateNo2flag.count(plate)&&plateNo2flag[plate] == 1){ plateNo2flag.erase(plate);return true;}else{return false;}});//添加谓词避免虚假唤醒return false;
}//扣费线程发起扣费请求...bool status = waitForEtcSignal(laneNo,plate,connTime);
if(status)
{//...
}//server线程收到扣费结果
//...
if(paySuccess)
{boost::mutex::scoped_lock lk(mutex mtx_etcSignal[laneNo]);plateNo2flag[plate] = 1;m_cond_etcSignal[laneNo].notify_all();
}

thread_group 线程组

        boost::thread_group 实际利用list<thread>管理一组线程,方便批量管理;如批量join;不是线程池,没有线程池的自动伸缩等功能。

        

bool TestServerClient::startServer()
{if (!m_bStarted){ if (!group){group = new boost::thread_group();}try{group->create_thread(boost::bind(&TestServerClient::func_1, this));group->add_thread(new boost::thread(boost::bind(&TestServerClient::func_2, this, "hello client")));//创建线程会自动加入list中(无法接受参数,需要bind) add添加线程m_bStarted = true;}catch (std::runtime_error e){std::string errorstr(e.what());}}return m_bStarted;
}void TestServerClient::stopServer()
{if (m_bStarted){group->interrupt_all();group->join_all();group = nullptr;}
}

 thread_pool

boost的线程池概述:

https://threadpool.sourceforge.net/index.html

 threadpool是基于[boost]库实现的一个线程池子库 .

/*! \file
* \brief Thread pool core.
*
* This file contains the threadpool's core class: pool<Task, SchedulingPolicy>.
*
* Thread pools are a mechanism for asynchronous and parallel processing 
* within the same process. The pool class provides a convenient way 
* for dispatching asynchronous tasks as functions objects. The scheduling
* of these tasks can be easily controlled by using customized schedulers. 
*
* Copyright (c) 2005-2007 Philipp Henkel
*
* Use, modification, and distribution are  subject to the
* Boost Software License, Version 1.0. (See accompanying  file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* http://threadpool.sourceforge.net
*
*/#ifndef THREADPOOL_POOL_HPP_INCLUDED
#define THREADPOOL_POOL_HPP_INCLUDED#include <boost/ref.hpp>#include "./detail/pool_core.hpp"#include "task_adaptors.hpp"#include "./detail/locking_ptr.hpp"#include "scheduling_policies.hpp"
#include "size_policies.hpp"
#include "shutdown_policies.hpp"/// The namespace threadpool contains a thread pool and related utility classes.
namespace boost { namespace threadpool
{/*! \brief Thread pool. ** Thread pools are a mechanism for asynchronous and parallel processing * within the same process. The pool class provides a convenient way * for dispatching asynchronous tasks as functions objects. The scheduling* of these tasks can be easily controlled by using customized schedulers. * A task must not throw an exception.** A pool is DefaultConstructible, CopyConstructible and Assignable.* It has reference semantics; all copies of the same pool are equivalent and interchangeable. * All operations on a pool except assignment are strongly thread safe or sequentially consistent; * that is, the behavior of concurrent calls is as if the calls have been issued sequentially in an unspecified order.** \param Task A function object which implements the operator 'void operator() (void) const'. The operator () is called by the pool to execute the task. Exceptions are ignored.* \param SchedulingPolicy A task container which determines how tasks are scheduled. It is guaranteed that this container is accessed only by one thread at a time. The scheduler shall not throw exceptions.** \remarks The pool class is thread-safe.* * \see Tasks: task_func, prio_task_func* \see Scheduling policies: fifo_scheduler, lifo_scheduler, prio_scheduler*/ template <typename Task                                   = task_func,template <typename> class SchedulingPolicy      = fifo_scheduler,template <typename> class SizePolicy            = static_size,template <typename> class SizePolicyController  = resize_controller,template <typename> class ShutdownPolicy        = wait_for_all_tasks> class thread_pool {typedef detail::pool_core<Task, SchedulingPolicy,SizePolicy,SizePolicyController,ShutdownPolicy> pool_core_type;shared_ptr<pool_core_type>          m_core; // pimpl idiomshared_ptr<void>                    m_shutdown_controller; // If the last pool holding a pointer to the core is deleted the controller shuts the pool down.public: // Type definitionstypedef Task task_type;                                   //!< Indicates the task's type.typedef SchedulingPolicy<task_type> scheduler_type;       //!< Indicates the scheduler's type./*   typedef thread_pool<Task, SchedulingPolicy,SizePolicy,ShutdownPolicy > pool_type;          //!< Indicates the thread pool's type.*/typedef SizePolicy<pool_core_type> size_policy_type; typedef SizePolicyController<pool_core_type> size_controller_type;public:/*! Constructor.* \param initial_threads The pool is immediately resized to set the specified number of threads. The pool's actual number threads depends on the SizePolicy.*/thread_pool(size_t initial_threads = 0): m_core(new pool_core_type), m_shutdown_controller(static_cast<void*>(0), bind(&pool_core_type::shutdown, m_core)){size_policy_type::init(*m_core, initial_threads);}/*! Gets the size controller which manages the number of threads in the pool. * \return The size controller.* \see SizePolicy*/size_controller_type size_controller(){return m_core->size_controller();}/*! Gets the number of threads in the pool.* \return The number of threads.*/size_t size()	const{return m_core->size();}/*! Schedules a task for asynchronous execution. The task will be executed once only.* \param task The task function object. It should not throw execeptions.* \return true, if the task could be scheduled and false otherwise. */  bool schedule(task_type const & task){	return m_core->schedule(task);}/*! Returns the number of tasks which are currently executed.* \return The number of active tasks. */  size_t active() const{return m_core->active();}/*! Returns the number of tasks which are ready for execution.    * \return The number of pending tasks. */  size_t pending() const{return m_core->pending();}/*! Removes all pending tasks from the pool's scheduler.*/  void clear(){ m_core->clear();}    /*! Indicates that there are no tasks pending. * \return true if there are no tasks ready for execution.	* \remarks This function is more efficient that the check 'pending() == 0'.*/   bool empty() const{return m_core->empty();}	/*! The current thread of execution is blocked until the sum of all active*  and pending tasks is equal or less than a given threshold. * \param task_threshold The maximum number of tasks in pool and scheduler.*/     void wait(size_t task_threshold = 0) const{m_core->wait(task_threshold);}	/*! The current thread of execution is blocked until the timestamp is met* or the sum of all active and pending tasks is equal or less * than a given threshold.  * \param timestamp The time when function returns at the latest.* \param task_threshold The maximum number of tasks in pool and scheduler.* \return true if the task sum is equal or less than the threshold, false otherwise.*/       bool wait(xtime const & timestamp, size_t task_threshold = 0) const{return m_core->wait(timestamp, task_threshold);}};/*! \brief Fifo pool.** The pool's tasks are fifo scheduled task_func functors.**/ typedef thread_pool<task_func, fifo_scheduler, static_size, resize_controller, wait_for_all_tasks> fifo_pool;/*! \brief Lifo pool.** The pool's tasks are lifo scheduled task_func functors.**/ typedef thread_pool<task_func, lifo_scheduler, static_size, resize_controller, wait_for_all_tasks> lifo_pool;/*! \brief Pool for prioritized task.** The pool's tasks are prioritized prio_task_func functors.**/ typedef thread_pool<prio_task_func, prio_scheduler, static_size, resize_controller, wait_for_all_tasks> prio_pool;/*! \brief A standard pool.** The pool's tasks are fifo scheduled task_func functors.**/ typedef fifo_pool pool;} } // namespace boost::threadpool#endif // THREADPOOL_POOL_HPP_INCLUDED

使用示例: 

// fifo策略的poolboost::threadpool::pool _thread_pool;
_thread_pool.size_controller().resize(4);
_thread_pool.schedule(boost::bind(&LedDevice::SendParkingLots, this, nBelongedPark));
//同步等待结束
_thread_pool.wait();// priority优先级线程池
#include <boost/thread.hpp>
#include "threadpool/pool.hpp"class HaiNanEtcInterface final:public EtcInterface
{
public://...enum Priority_Level{LowPriority = 100,MidPriority = 200,HighPriority = 300};//枚举声明 不定义不占内存 实际存在常量区(static 也在常量区)均可类名:访问
private:atomic_bool m_bStarted;boost::threadpool::prio_pool m_EtcThreadPool;
};bool HaiNanEtcInterface::startServer()
{if (!m_bStarted){
m_EtcThreadPool.size_controller().resize(4);//初始化线程池大小}m_bStarted = true;return m_bStarted;
}//使用优先级策略的线程池
void HaiNanEtcInterface::queryFee(const PassVehicle& pve)
{if (m_EtcThreadPool.size() > 1){		m_EtcThreadPool.schedule(boost::threadpool::prio_task_func(HighPriority, boost::bind(&HaiNanEtcInterface::queryFeeFunc, this,pve)));}
}void HaiNanEtcInterface::checkTime()
{if (m_EtcThreadPool.size() > 1){		m_EtcThreadPool.schedule(boost::threadpool::prio_task_func(LowPriority, boost::bind(&HaiNanEtcInterface::checkTimeFunc, this)));}
}void HaiNanEtcInterface::stopServer()
{if (m_bStarted){//清除pending的task 在等待所有active和pending的task结束m_EtcThreadPool.clear();m_EtcThreadPool.wait();}
}

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

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

相关文章

vmware_虚拟机安装zabbix_超快超简单

TIPS: 一开始用docker 和 安装包&#xff0c;安装zabbix总是有问题&#xff0c;后发现zabbix官方提供了装好的虚拟机 1、下载VMware pro 个人免费版 官网地址如下 https://support.broadcom.com/group/ecx/productdownloads?subfamilyVMwareWorkstationPro 如果提示注册&am…

服务器数据恢复—开盘修复raid5阵列硬盘故障的数据恢复案例

服务器存储数据恢复环境&#xff1a; 某品牌P2000存储&#xff0c;存储中有一组由8块硬盘&#xff08;包含一块热备盘&#xff09;组建的raid5阵列。上层部署VMWARE ESX虚拟化平台。 服务器存储故障&#xff1a; 存储在运行过程中有两块硬盘指示灯亮黄色。经过运维人员的初步检…

Go语言中GC(垃圾回收回收机制)三色标记与混合写屏障

5、Golang三色标记混合写屏障GC模式全分析 (yuque.com) 第1讲-课程目标_哔哩哔哩_bilibili Golang三色标记GC混合写屏障 Go V1.3之前的标记清除&#xff08;mark and sweep) 垃圾回收、内存管理、自动适放、三色标记法、STW (stop the world) 图的遍历&#xff1f;可达性分…

【Git】(基础篇二)—— Git操作

Git操作 在了解git理论知识之后&#xff0c;本文将结合实践操作为你讲解git的底层逻辑 Git的安装和配置 git官网下载&#xff1a;https://git-scm.com/ 下载后安装时除了选择安装地址外&#xff0c;其余都保持默认下一步即可。 安装好后鼠标右键会出现两个新的选项【Open …

基于 JAVA 的旅游网站设计与实现

点击下载源码 塞北村镇旅游网站设计 摘要 城市旅游产业的日新月异影响着村镇旅游产业的发展变化。网络、电子科技的迅猛前进同样牵动着旅游产业的快速成长。随着人们消费理念的不断发展变化&#xff0c;越来越多的人开始注意精神文明的追求&#xff0c;而不仅仅只是在意物质消…

项目JetCache的常见配置与使用

Hello, 大家好&#xff0c;今天本汪给大家带来的是JetCache在项目中的常见配置与用法讲解&#xff0c;接下来&#xff0c;随本汪一起来看看吧 一、介绍 官网地址&#xff1a;https://github.com/alibaba/jetcache JetCache 是一种 Java 缓存抽象&#xff0c;它为不同的缓存…

秘密,一般人我不告诉他.偷偷告诉你信创产品采购的正确打开方式:python爬虫实现

创作不易 只因热爱!! 热衷分享&#xff0c;一起成长! “你的鼓励就是我努力付出的动力” 采购XX有没有找你诉说 , 某某ZFCG网上的信创产品, 品种太多太杂,无法细分查找,某某详情页面要一个个看, 真费时费力,于是乎… !!!以下内容仅供学习使用,便于快速筛选找到需求产品!!!请勿…

【算法/序列】等差数列子序列算术序列最长对称子串

概念&#xff1a; 等差数列&#xff1a;任意两项的差总等于同一个常数 子数组 &#xff1a;是数组中的一个连续序列。 子序列&#xff1a;是通过从原序列删除零个或多个元素并在不改变顺序的情况下排列其余元素而获得的序列 算术序列&#xff1a;是一个数字列表&#xff0c;其中…

【时时三省】(C语言基础)变量

山不在高&#xff0c;有仙则名。水不在深&#xff0c;有龙则灵。 ——csdn时时三省 变量 可以改变的量 比如 int age&#xff1d;20 &#xff08;类型 变量的名字&#xff1d;0&#xff09; 如果后面要改可以直接代入 age&#xff1d;age1 age可以是任何字母 变量的分类…

【C++】类和对象的基本概念与使用

本文通过面向对象的概念以及通俗易懂的例子介绍面向对象引出类和对象。最后通过与之有相似之处的C语言中的struct一步步引出C中的类的定义方式&#xff0c;并提出了一些注意事项&#xff0c;最后描述了类的大小的计算方法。 一、什么是面向对象&#xff1f; 1.面向对象的概念 …

【C++编程】标准模板库 STL 的基本概念

STL 从广义上分为&#xff1a;容器、算法、迭代器 容器、算法之间通过迭代器进行无缝连接 STL 六大组件&#xff1a; 容器&#xff1a;各种数据结构&#xff0c;如 vector、list、deque、set、map 等&#xff0c;用来存放数据 序列式容器&#xff1a;物理存放上有序关联式容器&…

约束条件和数据库的用户管理

数据库的增删改查 查 约束条件和用户管理 删 约束条件&#xff1a; 主键 主键约束 primary key 用于标识表中的主键列的值&#xff0c;而且这个值是全表当中唯一的&#xff0c;而且值不能为null。 一个表只能有一个主键。 外键&#xff1a;用来建立表与表之间的关系。…

微信小游戏 彩色试管 倒水游戏 逻辑 (四)

最近开始研究微信小游戏&#xff0c;有兴趣的 可以关注一下 公众号&#xff0c; 记录一些心路历程和源代码。 定义了一个名为 WaterFlow class&#xff0c;该类继承自 cc.Graphics&#xff0c;用于在 Cocos Creator 中创建和显示水流的动画效果。下面是对代码的详细解释&#x…

FPGA FIR fdatool filter designer MATLAB

位数问题 fdatool 先确定输入信号的位宽&#xff0c;比如17位在fdatool中&#xff0c;选set quantization parameters 选input/output 设置input word length 为17bit(not confirmed) fir compiler implementation 注意&#xff1a; 当设置输入位宽为16位时&#xff0c;ip核…

Linux系统部署MySQL数据库

1.Linux插入光盘&#xff0c;使用df-h获取光盘信息&#xff0c;默认/dev/sr0文件为光盘文件 使用命令 mount -o ro /dev/sr0 /media进行手动挂载 mount -o ro /dev/sr0 /media 2.进入cd /etc/yum.repos.d目录 编辑配置yum库&#xff0c;编辑vim yum.repos [BaseOS] nameba…

Flutter 状态管理新境界:多Provider并行驱动UI

前言 在上一篇文章中&#xff0c;我们讨论了如何使用 Provider 在 Flutter 中进行状态管理。 本篇文章我们来讨论如何使用多个 Provider。 在 Flutter 中&#xff0c;使用 Provider 管理多个不同的状态时&#xff0c;你可以为每个状态创建一个单独的 ChangeNotifierProvider…

node+MySQL+Express实现账户登录,注册,重置之登录篇

nodeMySQLExpress实现账户登录 实现技术开发工具项目结构效果图app.js代码db.jsrouter下的account.jsdb下的account.jslogin.html数据库结构 实现技术 node.js,MySQL5.7(8.0以上版本会报错)&#xff0c;layui(前端框架)&#xff0c;Express notify(消息通知layui插件) 开发工…

如何使用在线工具将手机相册中的图片转换为JPG格式

我们经常在手机相册中保存大量的图片&#xff0c;无论是家庭聚会的照片还是旅行的瞬间&#xff0c;每一幅图像都承载着珍贵的记忆。然而&#xff0c;有时候我们会遇到图片格式不兼容的问题&#xff0c;尤其是在需要将图片分享到特定平台或编辑时。 例如&#xff0c;某些社交平台…

Java语音转文字及文字转语音教学 (离线版)

1. 语音转文字 1.1 maven导入以下包 <!-- 获取音频信息 --> <dependency><groupId>org</groupId><artifactId>jaudiotagger</artifactId><version>2.0.3</version> </dependency><!-- 语音识别 --> <dependen…

C++知识要点总结笔记

文章目录 前言一、c基础1.指针和引用指针和引用的区别函数指针 2.数据类型整型 short int long 和 long long无符号类型强制类型转换 3.关键字conststaticconst和static的区别define 和 typedef 的区别define 和 inline 的区别const和define的区别constexprvolatileextern前置与…