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

2020-01-06 14:01:59于海丽
  • }   
  • void TC_ThreadPool::stop()  { 
  • Lock sync(* this);   
  • std::vector< ThreadWorker *>::iterator it = _jobthread. begin();  while(it != _jobthread. end()) 
  • {  if ((*it)-> isAlive()) 
  • {  (*it)-> terminate(); 
  • (*it)-> getThreadControl().join ();  } 
  • ++it;  } 
  • _bAllDone = true;  } 
  •   void TC_ThreadPool::start() 
  • {  Lock sync(* this); 
  •   std::vector< ThreadWorker *>::iterator it = _jobthread. begin(); 
  • while(it != _jobthread. end())  { 
  • (*it)-> start();  ++it; 
  • }  _bAllDone = false; 
  • }   
  • bool TC_ThreadPool:: finish()  { 
  • return _startqueue. empty() && _jobqueue .empty() && _busthread. empty() && _bAllDone;  } 
  •   bool TC_ThreadPool::waitForAllDone( int millsecond) 
  • {  Lock sync( _tmutex); 
  •   start1: 
  • //任务队列和繁忙线程都是空的  if (finish ()) 
  • {  return true; 
  • }   
  • //永远等待  if(millsecond < 0) 
  • {  _tmutex.timedWait(1000); 
  • goto start1;  } 
  •   int64_t iNow = TC_Common:: now2ms(); 
  • int m = millsecond;  start2: 
  •   bool b = _tmutex.timedWait(millsecond); 
  • //完成处理了  if(finish ()) 
  • {  return true; 
  • }   
  • if(!b)  { 
  • return false;  } 
  •   millsecond = max((int64_t )0, m - (TC_Common ::now2ms() - iNow)); 
  • goto start2;   
  • return false;  } 
  •   TC_FunctorWrapperInterface *TC_ThreadPool::get( ThreadWorker *ptw)