深入解析C++编程中线程池的使用

2020-01-06 14:01:59于海丽

线程类的相关操作均十分简单。线程的执行入口是从Start()函数开始,其将调用函数ThreadFunction,ThreadFunction再调用实际的Run函数,执行实际的任务。

CThreadPool

CThreadPool是线程的承载容器,一般可以将其实现为堆栈、单向队列或者双向队列。在我们的系统中我们使用STL Vector对线程进行保存。CThreadPool的实现代码如下:

 

 
  1. class CThreadPool  { 
  2. friend class CWorkerThread;   
  3. private:  unsigned int m_MaxNum; //the max thread num that can create at the same time 
  4. unsigned int m_AvailLow; //The min num of idle thread that shoule kept  unsigned int m_AvailHigh; //The max num of idle thread that kept at the same time 
  5. unsigned int m_AvailNum; //the normal thread num of idle num;  unsigned int m_InitNum; //Normal thread num; 
  6.   protected: 
  7. CWorkerThread* GetIdleThread(void);   void AppendToIdleList(CWorkerThread* jobthread); 
  8. void MoveToBusyList(CWorkerThread* idlethread);  void MoveToIdleList(CWorkerThread* busythread); 
  9. void DeleteIdleThread(int num);  void CreateIdleThread(int num); 
  10.   public: 
  11. CThreadMutex m_BusyMutex; //when visit busy list,use m_BusyMutex to lock and unlock  CThreadMutex m_IdleMutex; //when visit idle list,use m_IdleMutex to lock and unlock 
  12. CThreadMutex m_JobMutex; //when visit job list,use m_JobMutex to lock and unlock  CThreadMutex m_VarMutex; 
  13. CCondition m_BusyCond; //m_BusyCond is used to sync busy thread list  CCondition m_IdleCond; //m_IdleCond is used to sync idle thread list 
  14. CCondition m_IdleJobCond; //m_JobCond is used to sync job list  CCondition m_MaxNumCond; 
  15.   vector<CWorkerThread*> m_ThreadList; 
  16. vector<CWorkerThread*> m_BusyList; //Thread List  vector<CWorkerThread*> m_IdleList; //Idle List