首页 > 编程 > C++ > 正文

c++实现简单的线程池

2020-05-23 14:13:09
字体:大 中 小
来源:转载
供稿:网友

这里给大家介绍了C++中对于pthread线程的一个简单应用以及使用继承CDoit,实现其中的start和end,有需要的小伙伴可以参考下

这是对pthread线程的一个简单应用

1. 实现了线程池的概念,线程可以重复使用。

2. 对信号量,互斥锁等进行封装,业务处理函数中只需写和业务相关的代码。

3. 移植性好。如果想把这个线程池代码应用到自己的实现中去,只要写自己的业务处理函数和改写工作队列数据的处理方法就可以了。

Sample代码主要包括一个主程序和两个线程实现类

ThreadTest.cpp:主程序

CThreadManager:线程管理Class,线程池的实现类

CThread:线程Class.

主程序实现方法。

1. 实现main函数和一个需要线程处理的业务函数(例子代码中业务函数是一个简单的计算函数Count)。在main函数中创建CThreadManager的实例,产生线程池。这个时候,把业务函数作为函数指针传到CThreadManager里面,最终会被线程调用。

2. 向工作队列中放入业务函数要处理的数据。

3. 设置信号量,唤醒线程。

 

 
  1. // 线程要执行的函数 
  2. int Count(int nWork) 
  3. { 
  4. int nResult = nWork * nWork; 
  5. printf("count result is %d/n",nResult); 
  6. return 0; 
  7. } 
  8. int main() { 
  9. // 创建线程管理类的实例,把要执行的线程函数和最大线程数传进去 
  10. CThreadManager* pManager = new CThreadManager(Count, 3); 
  11. // 把要进行计算的数放到工作队列中 
  12. pManager->PushWorkQue(5); 
  13. pManager->PushWorkQue(20); 
  14. // 设置信号量,唤醒线程 
  15. pManager->PostSem(); 
  16. pManager->PostSem(); 
  17. // 等待子线程执行 
  18. sleep(1); 
  19. return 0; 
  20. } 

CThreadManager实现的方法

1. 把信号量和互斥锁等封装成自己的函数

2. 在new方法里,循环调用CThread的new方法,启动一定数量(可设定)的线程,产生线程池。

3. 这些线程启动后,就会执行CThreadManager中的ManageFuction函数。这个函数是无限循环的,保证了线程在整个程序的生命周期中不销毁。

4. 在循环处理里面,第一行代码就是等待一个信号量,这个信号量是由主程序进行设置的,这个信号信号量如果没有被设置(代表暂时没有需要处理的工作),所有线程都在这里阻塞着。

4. 一旦信号量被设置,根据Linux线程调度机制,在阻塞的线程队列中,其中一个线程被唤醒,可以执行后面的代码。

5. 从工作队列中取出要进行处理的数据(使用互斥锁进行排他)

6. 通过函数指针调用main函数传过来的业务函数,处理数据。

7. 业务函数执行完之后,线程进入下一个循环,等待新的信号量。

 

 
  1. class CThreadManager { 
  2. friend void* ManageFuction(void*); 
  3. private: 
  4. sem_t m_sem; // 信号量 
  5. pthread_mutex_t m_mutex; // 互斥锁 
  6. queue<int> m_queWork; // 工作队列 
  7. list<CThread*> m_lstThread; // 线程list 
  8. int (*m_threadFuction)(int); //函数指针,指向main函数传过来的线程执行函数 
  9. public: 
  10. CThreadManager(int (*threadFuction)(int), int nMaxThreadCnt); 
  11. virtual ~CThreadManager(); 
  12. int WaitSem(); 
  13. int PostSem(); 
  14. int LockMutex(); 
  15. int UnlockMutex(); 
  16. void PushWorkQue(int nWork); 
  17. int PopWorkQue(); 
  18. int RunThreadFunction(int nWork); 
  19. }; 
  20. // 线程执行函数,它只是个壳子,处理信号量和互斥锁等, 
  21. // 最后调用main函数传过来的线程执行函数来实现业务处理 
  22. void* ManageFuction(void* argv) 
  23. { 
  24. CThreadManager* pManager = (CThreadManager*)argv; 
  25. // 进行无限循环(意味着线程是不销毁的,重复利用) 
  26. while(true) 
  27. { 
  28. // 线程开启后,就在这里阻塞着,直到main函数设置了信号量 
  29. pManager->WaitSem(); 
  30. printf("thread wakeup./n"); 
  31. // 从工作队列中取出要处理的数 
  32. pManager->LockMutex(); 
  33. int nWork = pManager->PopWorkQue(); 
  34. pManager->UnlockMutex(); 
  35. printf("call Count function./n"); 
  36. pManager->RunThreadFunction(nWork); 
  37. } 
  38. return 0; 
  39. } 
  40. // 构造方法 
  41. CThreadManager::CThreadManager(int (*threadFuction)(int), int nMaxThreadCnt)  
  42. { 
  43. sem_init(&m_sem, 0, 0); 
  44. pthread_mutex_init(&m_mutex, NULL); 
  45. m_threadFuction = threadFuction; 
  46. for(int i=0; i<nMaxThreadCnt; i++) 
  47. { 
  48. CThread* pThread = new CThread(ManageFuction, this); 
  49. printf("thread started./n"); 
  50. m_lstThread.push_back(pThread); 
  51. } 
  52. } 

CThread实现的方法

CThreadManager比较简单,封装了创建线程和join线程的函数。

 

 
  1. CThread::CThread(void* (*threadFuction)(void*),void* threadArgv)  
  2. { 
  3. // 初始化线程属性 
  4. pthread_attr_t threadAttr; 
  5. pthread_attr_init(&threadAttr); 
  6.  
  7. pthread_create(&m_thread, &threadAttr, threadFuction, threadArgv); 
  8. } 

c++线程池,继承CDoit,实现其中的start和end

 

 
  1. /* 
  2. * 多线程管理类 
  3. *  
  4. */ 
  5.  
  6. #ifndef CTHREADPOOLMANAGE_H 
  7. #define CTHREADPOOLMANAGE_H 
  8. #include <iostream> 
  9. #include <pthread.h> 
  10. #include <unistd.h>  
  11. #include <list> 
  12. #include <vector> 
  13. #include <time.h> 
  14. #include <asm/errno.h> 
  15.  
  16. #define USLEEP_TIME 100 
  17. #define CHECK_TIME 1 
  18.  
  19.  
  20. using namespace std; 
  21. class CDoit 
  22. { 
  23. public: 
  24. virtual int start(void *){}; 
  25. virtual int end(){}; 
  26. }; 
  27.  
  28.  
  29. class CthreadPoolManage 
  30. { 
  31. private: 
  32. int _minThreads; //最少保留几个线程 
  33. int _maxThreads; //最多可以有几个线程 
  34. int _waitSec; //空闲多少秒后将线程关闭 
  35. class threadInfo{ 
  36. public: 
  37. threadInfo(){ 
  38. isbusy = false;  
  39. doFlag = true; 
  40. } 
  41. // 
  42. pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER; 
  43. pthread_cond_t cond=PTHREAD_COND_INITIALIZER; 
  44. bool isbusy; //是否空闲 
  45. bool doFlag; 
  46. // 
  47. time_t beginTime; //线程不工作开始时间 
  48. pthread_t cThreadPid; //线程id 
  49. pthread_attr_t cThreadAttr; //线程属性 
  50. CDoit * doit; //任务类 
  51. void * value; //需要传递的值 
  52. }; 
  53. //线程函数 
  54. static void* startThread(void*); 
  55. //任务队列锁 
  56. pthread_mutex_t _duty_mutex; 
  57. //任务队列 
  58. list<threadInfo*> _dutyList; 
  59. //线程队列锁 
  60. pthread_mutex_t _thread_mutex; 
  61. //线程队列 
  62. list<threadInfo*> _threadList; 
  63.  
  64. ///初始化,创建最小个数线程/// 
  65. void initThread();  
  66. ///任务分配线程/// 
  67. static void* taskAllocation(void*arg); 
  68. pthread_t tasktPid; 
  69. ///线程销毁、状态检查线程/// 
  70. static void* checkThread(void* arg); 
  71. pthread_t checktPid; 
  72. bool checkrun; 
  73.  
  74. //线程异常退出清理 
  75. static void threadCleanUp(void* arg); 
  76.  
  77. // 
  78. int addThread(list<threadInfo*> *plist,threadInfo* ptinfo); 
  79.  
  80. public: 
  81. CthreadPoolManage(); 
  82. /* 
  83. 保留的最少线程,最多线程数,空闲多久销毁,保留几个线程的冗余 
  84. */ 
  85. CthreadPoolManage(int min,int max,int waitSec); 
  86. ~CthreadPoolManage(); 
  87.  
  88. int start(); 
  89. //任务注入器 
  90. int putDuty(CDoit *,void *); 
  91.  
  92. int getNowThreadNum(); 
  93.  
  94. }; 
  95.  
  96. #endif // CTHREADPOOLMANAGE_H 

CPP

 

 
  1. /* 
  2. * 线程池,线程管理类 
  3. *  
  4. */ 
  5.  
  6. #include "cthreadpoolmanage.h" 
  7.  
  8. CthreadPoolManage::CthreadPoolManage() 
  9. { 
  10. _minThreads = 5; //最少保留几个线程 
  11. _maxThreads = 5; //最多可以有几个线程 
  12. _waitSec = 10; //空闲多少秒后将线程关闭 
  13. pthread_mutex_init(&_duty_mutex, NULL); 
  14. pthread_mutex_init(&_thread_mutex, NULL); 
  15. checkrun = true; 
  16. } 
  17.  
  18.  
  19. CthreadPoolManage::CthreadPoolManage(int min, int max, int waitSec) 
  20. { 
  21. CthreadPoolManage(); 
  22. _minThreads = min; //最少保留几个线程 
  23. _maxThreads = max; //最多可以有几个线程 
  24. _waitSec = waitSec; //空闲多少秒后将线程关闭 
  25. } 
  26.  
  27. CthreadPoolManage::~CthreadPoolManage() 
  28. { 
  29.  
  30. } 
  31. void CthreadPoolManage::threadCleanUp(void* arg) 
  32. { 
  33. threadInfo* tinfo = (threadInfo*)arg; 
  34. tinfo->isbusy = false; 
  35. pthread_mutex_unlock(&tinfo->mtx); 
  36. pthread_attr_destroy (&tinfo->cThreadAttr); 
  37. delete tinfo; 
  38. } 
  39.  
  40. void* CthreadPoolManage::startThread(void* arg) 
  41. { 
  42. cout<<"线程开始工作"<<endl; 
  43. threadInfo* tinfo = (threadInfo*)arg; 
  44. pthread_cleanup_push(threadCleanUp,arg); 
  45. while(tinfo->doFlag){ 
  46. pthread_mutex_lock(&tinfo->mtx); 
  47. if(tinfo->doit == NULL) 
  48. { 
  49. cout<<"开始等待任务"<<endl; 
  50. pthread_cond_wait(&tinfo->cond,&tinfo->mtx); 
  51. cout<<"有任务了"<<endl; 
  52. } 
  53. tinfo->isbusy = true; 
  54. tinfo->doit->start(tinfo->value); 
  55. tinfo->doit->end(); 
  56. tinfo->doit=NULL; 
  57. tinfo->isbusy = false; 
  58. time( &tinfo->beginTime); 
  59. pthread_mutex_unlock(&tinfo->mtx); 
  60. } 
  61. //0正常执行到这儿不执行清理函数,异常会执行 
  62. pthread_cleanup_pop(0); 
  63. pthread_attr_destroy (&tinfo->cThreadAttr); 
  64. delete tinfo; 
  65. cout<<"线程结束"<<endl; 
  66. } 
  67.  
  68. void CthreadPoolManage::initThread() 
  69. { 
  70. int i = 0; 
  71. for(i = 0;i<this->_minThreads;i++) 
  72. { 
  73. threadInfo *tinfo = new threadInfo; 
  74. tinfo->doit = NULL; 
  75. tinfo->value = NULL; 
  76. tinfo->isbusy = false; 
  77. tinfo->doFlag = true; 
  78. // PTHREAD_CREATE_DETACHED (分离线程) 和 PTHREAD _CREATE_JOINABLE (非分离线程) 
  79. pthread_attr_init(&tinfo->cThreadAttr); 
  80. pthread_attr_setdetachstate(&tinfo->cThreadAttr,PTHREAD_CREATE_DETACHED ); 
  81. cout<<"初始化了一个线程"<<endl; 
  82. if(pthread_create(&tinfo->cThreadPid,&tinfo->cThreadAttr,startThread,(void *)tinfo) != 0) 
  83. { 
  84. cout<<"创建线程失败"<<endl; 
  85. break; 
  86. } 
  87. this->_threadList.push_back(tinfo); 
  88. } 
  89. } 
  90.  
  91. int CthreadPoolManage::addThread(std::list< CthreadPoolManage::threadInfo* >* plist, CthreadPoolManage::threadInfo* ptinfo) 
  92. { 
  93. threadInfo *tinfo = new threadInfo; 
  94. tinfo->doit = ptinfo->doit; 
  95. tinfo->value = ptinfo->value; 
  96. tinfo->isbusy = true; 
  97. if(pthread_create(&tinfo->cThreadPid,NULL,startThread,(void *)tinfo) != 0) 
  98. { 
  99. cout<<"创建线程失败"<<endl; 
  100. return -1; 
  101. } 
  102. plist->push_back(tinfo); 
  103. return 0; 
  104. } 
  105.  
  106.  
  107. int CthreadPoolManage::putDuty(CDoit* doit, void* value) 
  108. { 
  109. threadInfo *tinfo = new threadInfo; 
  110. time( &tinfo->beginTime); 
  111. tinfo->doit= doit; 
  112. tinfo->value = value; 
  113. pthread_mutex_lock(&_duty_mutex); 
  114. this->_dutyList.push_back(tinfo); 
  115. pthread_mutex_unlock(&_duty_mutex); 
  116. return 0; 
  117. } 
  118.  
  119. void* CthreadPoolManage::taskAllocation(void*arg) 
  120. { 
  121. CthreadPoolManage * ptmanage = (CthreadPoolManage*)arg; 
  122. int size_1 = 0; 
  123. int size_2 = 0; 
  124. int i_1 = 0; 
  125. int i_2 = 0; 
  126. bool a_1 = true; 
  127. bool a_2 = true; 
  128. threadInfo* ptinfo; 
  129. threadInfo* ptinfoTmp; 
  130. while(true){ 
  131. size_1 = 0; 
  132. size_2 = 0; 
  133. pthread_mutex_lock(&ptmanage->_duty_mutex); 
  134. pthread_mutex_lock(&ptmanage->_thread_mutex); 
  135. size_1 = ptmanage->_dutyList.size(); 
  136. size_2 =ptmanage->_threadList.size(); 
  137. for(list<threadInfo*>::iterator itorti1 = ptmanage->_dutyList.begin();itorti1 !=ptmanage->_dutyList.end();) 
  138. { 
  139. ptinfo = *itorti1; 
  140. a_1 = true; 
  141. for(list<threadInfo*>::iterator itorti2 = ptmanage->_threadList.begin();itorti2!=ptmanage->_threadList.end();itorti2++){ 
  142. ptinfoTmp = *itorti2; 
  143. if(EBUSY == pthread_mutex_trylock(&ptinfoTmp->mtx)) 
  144. { 
  145. continue; 
  146. } 
  147. if(!ptinfoTmp->isbusy) 
  148. { 
  149. ptinfoTmp->doit = ptinfo->doit; 
  150. ptinfoTmp->value = ptinfo->value; 
  151. ptinfoTmp->isbusy = true; 
  152. pthread_cond_signal(&ptinfoTmp->cond); 
  153. pthread_mutex_unlock(&ptinfoTmp->mtx); 
  154. a_1 = false; 
  155. delete ptinfo; 
  156. break; 
  157. } 
  158. pthread_mutex_unlock(&ptinfoTmp->mtx); 
  159. } 
  160. if(a_1){ 
  161. if(ptmanage->_threadList.size()>ptmanage->_maxThreads||ptmanage->addThread(&ptmanage->_threadList,ptinfo)!=0) 
  162. { 
  163. itorti1++; 
  164. continue; 
  165. }else{ 
  166. itorti1 = ptmanage->_dutyList.erase(itorti1); 
  167. } 
  168. delete ptinfo; 
  169. }else{ 
  170. itorti1 = ptmanage->_dutyList.erase(itorti1); 
  171. } 
  172. } 
  173. pthread_mutex_unlock(&ptmanage->_duty_mutex); 
  174. pthread_mutex_unlock(&ptmanage->_thread_mutex); 
  175. usleep(USLEEP_TIME); 
  176. } 
  177. return 0; 
  178. } 
  179.  
  180. void* CthreadPoolManage::checkThread(void* arg) 
  181. { 
  182. CthreadPoolManage * ptmanage = (CthreadPoolManage*)arg; 
  183. threadInfo* ptinfo; 
  184. time_t nowtime; 
  185. while(ptmanage->checkrun){ 
  186. sleep(CHECK_TIME); 
  187. pthread_mutex_lock(&ptmanage->_thread_mutex); 
  188. if(ptmanage->_threadList.size()<=ptmanage->_minThreads) 
  189. { 
  190. pthread_mutex_unlock(&ptmanage->_thread_mutex); 
  191. continue; 
  192. } 
  193. for(list<threadInfo*>::iterator itorti2 = ptmanage->_threadList.begin();itorti2!=ptmanage->_threadList.end();){ 
  194. ptinfo = *itorti2; 
  195. if(EBUSY == pthread_mutex_trylock(&ptinfo->mtx)) 
  196. { 
  197. itorti2++; 
  198. continue; 
  199. } 
  200. time(&nowtime); 
  201. if(ptinfo->isbusy == false && nowtime-ptinfo->beginTime>ptmanage->_waitSec) 
  202. { 
  203. ptinfo->doFlag = false; 
  204. itorti2 = ptmanage->_threadList.erase(itorti2); 
  205. }else{ 
  206. itorti2++; 
  207. } 
  208. pthread_mutex_unlock(&ptinfo->mtx); 
  209. } 
  210. pthread_mutex_unlock(&ptmanage->_thread_mutex); 
  211. } 
  212. } 
  213.  
  214. int CthreadPoolManage::start() 
  215. { 
  216. //初始化 
  217. this->initThread(); 
  218. //启动任务分配线程 
  219. if(pthread_create(&tasktPid,NULL,taskAllocation,(void *)this) != 0) 
  220. { 
  221. cout<<"创建任务分配线程失败"<<endl; 
  222. return -1; 
  223. } 
  224. //创建现程状态分配管理线程 
  225. if(pthread_create(&checktPid,NULL,checkThread,(void *)this) != 0) 
  226. { 
  227. cout<<"创建线程状态分配管理线程失败"<<endl; 
  228. return -1; 
  229. } 
  230. return 0; 
  231. } 
  232.  
  233. /////////////////////////////// 
  234. int CthreadPoolManage::getNowThreadNum() 
  235. { 
  236. int num = 0; 
  237. pthread_mutex_lock(&this->_thread_mutex); 
  238. num = this->_threadList.size(); 
  239. pthread_mutex_unlock(&this->_thread_mutex); 
  240. return num ; 
  241. } 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表