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

2020-01-06 14:01:59于海丽
  • void init(size_t num);   
  • /**  * @brief 获取线程个数. 
  • *  * @return size_t 线程个数 
  • */  size_t getThreadNum() { Lock sync(* this); return _jobthread. size(); } 
  •   /** 
  • * @brief 获取线程池的任务数( exec添加进去的).  * 
  • * @return size_t 线程池的任务数  */ 
  • size_t getJobNum() { return _jobqueue. size(); }   
  • /**  * @brief 停止所有线程 
  • */  void stop(); 
  •   /** 
  • * @brief 启动所有线程  */ 
  • void start();   
  • /**  * @brief 启动所有线程并, 执行初始化对象. 
  • *   * @param ParentFunctor 
  • * @param tf  */ 
  • template<class ParentFunctor>  void start(const TC_FunctorWrapper< ParentFunctor> &tf) 
  • {  for(size_t i = 0; i < _jobthread .size(); i++) 
  • {  _startqueue. push_back(new TC_FunctorWrapper<ParentFunctor >(tf)); 
  • }   
  • start();  } 
  •   /** 
  • * @brief 添加对象到线程池执行,该函数马上返回,  * 线程池的线程执行对象 
  • */  template<class ParentFunctor> 
  • void exec(const TC_FunctorWrapper< ParentFunctor> &tf)  { 
  • _jobqueue.push_back(new TC_FunctorWrapper<ParentFunctor >(tf));  } 
  •   /** 
  • * @brief 等待所有工作全部结束(队列无任务, 无空闲线程).  * 
  • * @param millsecond 等待的时间( ms), -1:永远等待  * @return true, 所有工作都处理完毕 
  • * false,超时退出  */ 
  • bool waitForAllDone(int millsecond = -1);   
  • public:   
  • /**  * @brief 线程数据基类,所有线程的私有数据继承于该类