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

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

此处jobThread队列初始化后不会改变(因为没有实现自增长功能),所以非线程安全的vector队列即可,busthread的忙碌线程队列会被移进移出,但是操作会自带Lock sync( _tmutex),该互斥量是线程池本身继承的,所以是共有的,也无需另外使用线程安全的TC_ThreadQueue,使用vector即可。

TC_ThreadPool:: idle中的

 

 
  1. if( _busthread. empty())  { 
  2. _bAllDone = true;  _tmutex.notifyAll(); 

主要用于当线程池工作起来后的waitForAllDone方法:

 

 
  1. bool TC_ThreadPool:: waitForAllDone( int millsecond)  { 
  2. Lock sync( _tmutex);   
  3. start1:  //任务队列和繁忙线程都是空的 
  4. if (finish())  { 
  5. return true;  } 
  6.   //永远等待 
  7. if(millsecond < 0)  { 
  8. _tmutex.timedWait(1000);  goto start1; 
  9. }   
  10. int64_t iNow = TC_Common:: now2ms();  int m = millsecond; 
  11. start2:   
  12. bool b = _tmutex.timedWait(millsecond);  //完成处理了 
  13. if(finish())  { 
  14. return true;  } 
  15.   if(!b) 
  16. {  return false; 
  17. }   
  18. millsecond = max((int64_t )0, m - (TC_Common ::now2ms() - iNow));  goto start2;