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

2020-01-06 14:01:59于海丽
  • {   
  • TC_FunctorWrapperInterface *pFunctorWrapper = NULL;  if(! _jobqueue. pop_front(pFunctorWrapper, 1000)) 
  • {  return NULL; 
  • }   
  • {  Lock sync( _tmutex); 
  • _busthread. insert(ptw);  } 
  • return pFunctorWrapper;  } 
  •   TC_FunctorWrapperInterface *TC_ThreadPool::get() 
  • {  TC_FunctorWrapperInterface *pFunctorWrapper = NULL; 
  • if(! _startqueue. pop_front(pFunctorWrapper))  { 
  • return NULL;  } 
  •   return pFunctorWrapper; 
  • }   
  • void TC_ThreadPool::idle( ThreadWorker *ptw)  { 
  • Lock sync( _tmutex);  _busthread. erase(ptw); 
  •   //无繁忙线程, 通知等待在线程池结束的线程醒过来 
  • if( _busthread. empty())  { 
  • _bAllDone = true;  _tmutex.notifyAll(); 
  • }  } 
  •   void TC_ThreadPool::notifyT() 
  • {  _jobqueue. notifyT(); 
  • 线程池使用后记

    线程池适合场合

    事 实上,线程池并不是万能的。它有其特定的使用场合。线程池致力于减少线程本身的开销对应用所产生的影响,这是有前提的,前提就是线程本身开销与线程执行任 务相比不可忽略。如果线程本身的开销相对于线程任务执行开销而言是可以忽略不计的,那么此时线程池所带来的好处是不明显的,比如对于FTP服务器以及Telnet服务器,通常传送文件的时间较长,开销较大,那么此时,我们采用线程池未必是理想的方法,我们可以选择“即时创建,即时销毁”的策略。