博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++线程池小例子
阅读量:6717 次
发布时间:2019-06-25

本文共 5964 字,大约阅读时间需要 19 分钟。

ThreadPool.h

#ifndef __THREADPOOL_H #define __THREADPOOL_H#define HAVE_STRUCT_TIMESPEC//#include "servant/Application.h"#include 
#include
#include
using namespace std;/*** 执行任务的类,设置任务数据、定义执行方法(纯虚函数)*/class CTask{protected: string m_strTaskName; //任务的名称 void* m_ptrData; //具体数据public: CTask() {} CTask(string taskName) { m_strTaskName = taskName; m_ptrData = NULL; } virtual int Run() = 0; //任务执行方法 void SetData(void* data); //设置任务数据public: virtual ~CTask() {}};/*** 线程结构体*/struct CThread{ pthread_t pthread_id; //线程id int iStat; //线程状态 CThread() : iStat(0) { } bool operator == (const CThread &obj) const { return (long)&pthread_id == (long)&obj.pthread_id; }};/*** 线程池管理类的实现*/class CThreadPool{public: CThreadPool(int threadNum = 10); int AddTask(CTask *task); //把任务添加到任务队列中 int getTaskSize(); //获取当前任务队列中的任务数 int StopAll(); //使线程池中的线程退出protected: int Create(); //创建线程池中的线程 static void* ThreadFunc(void * threadData); //新线程的线程回调函数 static int MoveToIdle(CThread *pThread); //线程执行结束后,状态置为空闲0 static int MoveToBusy(CThread *pThread); //线程开始执行,状态置为运行1private: static vector
m_vecTaskList; //任务列表 static bool shutdown; //线程退出标志 int m_iThreadNum; //线程池中启动的线程数 static vector
m_vecThread; //线程列表 static pthread_mutex_t m_pthreadMutex; //线程同步锁 static pthread_cond_t m_pthreadCond; //线程同步的条件变量};#endif

  

ThreadPool.cpp

#include "ThreadPool.h"  #include 
#include
using namespace std;void CTask::SetData(void * data){ m_ptrData = data;}vector
CThreadPool::m_vecTaskList; //任务列表 bool CThreadPool::shutdown = false;vector
CThreadPool::m_vecThread; //线程列表pthread_mutex_t CThreadPool::m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t CThreadPool::m_pthreadCond = PTHREAD_COND_INITIALIZER;/*** 线程池管理类构造函数*/CThreadPool::CThreadPool(int threadNum){ this->m_iThreadNum = threadNum; cout << "threadNum:" << threadNum << " threads will be created." << endl; Create(); //创建线程}/*** 创建线程*/int CThreadPool::Create(){ m_vecThread.resize(m_iThreadNum); for (size_t i = 0; i < m_vecThread.size(); i++) { pthread_create(&m_vecThread[i].pthread_id, NULL, ThreadFunc, &m_vecThread[i]); } return 0;}/*** 线程回调函数*/void* CThreadPool::ThreadFunc(void* threadData){ CThread *pThread = (CThread*)threadData; while (1) { pthread_mutex_lock(&m_pthreadMutex); //lock while (m_vecTaskList.size() == 0 && !shutdown) { pthread_cond_wait(&m_pthreadCond, &m_pthreadMutex); /* pthread_cond_wait前要先加锁 pthread_cond_wait把线程放进阻塞队列后,内部会解锁,然后等待条件变量被其它线程唤醒 pthread_cond_wait被唤醒后会再自动加锁 */ } if (shutdown) { pthread_mutex_unlock(&m_pthreadMutex); cout << "thread:" << (long)&pThread->pthread_id << " will exit." << endl; pthread_exit(NULL); } //线程状态置1 MoveToBusy(pThread); //取出一个任务 CTask* task = NULL; vector
::iterator iter = m_vecTaskList.begin(); if (iter != m_vecTaskList.end()) { task = *iter; m_vecTaskList.erase(iter); } pthread_mutex_unlock(&m_pthreadMutex); //unlock //执行任务 if (task) { task->Run(); } //线程状态置0 MoveToIdle(pThread); } return (void*)0;}int CThreadPool::MoveToIdle(CThread *pThread){ vector
::iterator iter_thread = std::find(m_vecThread.begin(), m_vecThread.end(), *pThread); if (iter_thread != m_vecThread.end()) { iter_thread->iStat = 0; cout << "tid:" << (long)&pThread->pthread_id << " idle." << endl; } return 0;}int CThreadPool::MoveToBusy(CThread *pThread){ vector
::iterator iter_thread = std::find(m_vecThread.begin(), m_vecThread.end(), *pThread); if (iter_thread != m_vecThread.end()) { iter_thread->iStat = 1; cout << "tid:" << (long)&pThread->pthread_id << " run." << endl; } return 0;}/*** 往任务队列里边添加任务并发出线程同步信号*/int CThreadPool::AddTask(CTask *task){ pthread_mutex_lock(&m_pthreadMutex); this->m_vecTaskList.push_back(task); pthread_cond_signal(&m_pthreadCond); pthread_mutex_unlock(&m_pthreadMutex); return 0;}/*** 获取当前队列中任务数*/int CThreadPool::getTaskSize(){ return m_vecTaskList.size();}/*** 停止所有线程*/int CThreadPool::StopAll(){ /** 避免重复调用 */ if (shutdown) { return -1; } cout << "All threads will be stoped." << endl; /** 唤醒所有等待线程,线程池要销毁了 */ shutdown = true; pthread_cond_broadcast(&m_pthreadCond); /** 阻塞等待线程退出,否则就成僵尸了 */ for (size_t i = 0; i < m_vecThread.size(); i++) { pthread_join(m_vecThread[i].pthread_id, NULL); } m_vecThread.clear(); /** 销毁条件变量和互斥体 */ pthread_mutex_destroy(&m_pthreadMutex); pthread_cond_destroy(&m_pthreadCond); return 0;}

  

main.cpp

#include 
#include "ThreadPool.h"using namespace std;class CMyTask : public CTask{public: CMyTask() {} inline int Run() { cout << (char*)this->m_ptrData << endl; return 0; }};int main(){ CThreadPool threadPool(10); CMyTask taskObj; char szTmp[] = "this is the first thread running"; taskObj.SetData((void*)szTmp); for (int i = 0; i < 10; i++) { threadPool.AddTask(&taskObj); } while (1) { cout << "there are still " << threadPool.getTaskSize() << " tasks need to handle" << endl; if (threadPool.getTaskSize() == 0) { if (threadPool.StopAll() == -1) { cout << "Now I will exit from main" << endl; return 0; } } } return 0;}

  

makeflie

TARGET:=threadpoolINC:= -I./LIB_PATH:=LIB:= -lpthreadCFLAGS:=-Wall -g -O0 -D_REENTRANT -Wl,-rpath=./ $(INC) $(LIB_PATH)CPPFLAGS:=$(CFLAGS)SRC:=$(shell echo *.cpp)OBJ:=$(patsubst %.cpp,%.o,$(SRC))all: $(TARGET)$(TARGET): $(OBJ)	$(CXX) $^ $(CFLAGS) $(LIB) -o $@clean:	rm -f $(OBJ)	rm -f $(TARGET)

  

windows下配置 pthread 参见:

转载于:https://www.cnblogs.com/SZxiaochun/p/9625770.html

你可能感兴趣的文章
常用SQL汇总(Java开发)
查看>>
vue跳转传参刷新后参数消失
查看>>
Python基本数据类型之时间
查看>>
01Go命令介绍
查看>>
【spring boot2】第4篇:spring boot对静态资源的管理
查看>>
python3 使用argparse更好的组织输入参数
查看>>
Flutter 环境搭建以及创建第一个APP遇到的坑
查看>>
mybatis连表查询
查看>>
【跃迁之路】【694天】程序员高效学习方法论探索系列(实验阶段451-2019.1.14)...
查看>>
[中级] Func() 和 ObjBindMethod() 的关系
查看>>
垃圾回收机制
查看>>
C语言实现一个简易的Hash table(6)
查看>>
【javascript】实现模板生成大量数据
查看>>
win32拖拽编程
查看>>
使用 LineBasedFrameDecoder 和 StringDecoder 解决半包粘包问题
查看>>
分布式缓存Redis使用心得
查看>>
【修真院“善良”系列之三】技术面试的时候该怎么样介绍自己?
查看>>
聊聊flink的EventTime
查看>>
TypeScript 类
查看>>
React 的几种条件渲染以及选择
查看>>