C++怎么实现一个简单的线程池
发表于:2025-02-23 作者:千家信息网编辑
千家信息网最后更新 2025年02月23日,本文小编为大家详细介绍"C++怎么实现一个简单的线程池",内容详细,步骤清晰,细节处理妥当,希望这篇"C++怎么实现一个简单的线程池"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知
千家信息网最后更新 2025年02月23日C++怎么实现一个简单的线程池
本文小编为大家详细介绍"C++怎么实现一个简单的线程池",内容详细,步骤清晰,细节处理妥当,希望这篇"C++怎么实现一个简单的线程池"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
一、设计
线程池应该包括
保存线程的容器,保存任务的容器。
为了能保证避免线程对任务的竞态获取,需要对任务队列进行加锁。
为了使得工作线程感知任务的到来,需要使用条件变量来唤醒工作线程。
任务容器中的任务管理。
任务的处理API。
二、参数选择
使用数组存放线程,链表存放任务。
三、类设计
线程池类
templateclass threadpool{public: threadpool(int thread_num,int max_request); ~threadpool(); bool append(T* request); // 在任务队列中添加任务private: static void worker(void* arg); void run();private: int m_thread_num; // 线程池中的线程数 int m_max_request; // 任务队列最大保存的任务数 pthread_t *m_threads; // 保存线程的容器 std::list m_queuework; // 保存任务的链表 sem m_sem; // 通知工作线程任务到来 lock m_locker; // 互斥访问任务队列};
构造函数
templatethreadpool ::threadpool(int thread_num,int max_request):m_thread_num(thread_num),m_max_request(max_request){ if(thread_num <=0 || max_request <= 0) throw std::exception(); m_threads = new pthread_t[thread_num]; if(!m_threads) throw std::exception(); for(int i = 0;i < thread_num;++i) { // 创建线程 if(pthread_create(m_threads + i, NULL,worker,this)!=0) { delete[] m_threads; throw std::exception(); } // 分离线程 if(pthread_detach(m_threads[i])) { delete[] m_threads; throw std::exception(); } }}
析构函数
templatethreadpool ::~threadpool(){ delete[] m_trheads;}
添加任务函数
templatebool threadpool ::append(T* request){ m_locker.lock(); if(m_queuework.size() > m_max_request) { m_locker.unlock(); return false; } m_queuework.push_back(request); m_locker.unlock(); m_sem.post(); return true;}
任务处理函数
templatevoid* threadpool ::worker(void*arg){ threadpool* pool = (threadpool*)arg; pool->run(); return pool;}template void threadpool ::run(){ while(true) { m_sem.wait(); m_locker.lock(); if(m_queuework.empty()) { m_locker.unlock(); continue; } T* request = m_queuework.front(); m_queuework.pop_front(); m_locker.unlock(); request.process(); // 具体任务的处理业务 }}
读到这里,这篇"C++怎么实现一个简单的线程池"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
任务
线程
函数
容器
队列
处理
C++
文章
工作
内容
设计
妥当
最大
业务
参数
变量
思路
数组
新知
更多
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
软件开发有限公司合作
网络安全中什么是非法存取
斑马(广州)互联网科技有限公司
oracle最新数据库
数据库实体图描述
国软培训网络安全
信息安全与网络安全一样吗
平原软件开发
河北安卓软件开发哪里有
济南市网络安全公益作品
kdb数据库+安装
物业管理软件开发
8268cpu服务器
闵行区库存网络技术生产过程
深圳中辉互联网科技怎么样
前端数据库开发培训
计算机三级网络技术报名要求
一心互联网络科技
数据库管理 dba的负责
软件开发需不需要学英语
软件开发不允许预付
怎么导入源码去数据库
ps4无法登入服务器4204
数据库外键和主键先建哪一个
tbc战场服务器通用么
数据库变量定义sql语句
学校网络安全手抄报简单漂亮
sql如何显示数据库前三条记录
上海孚正网络技术有限公司
债券数据库python