c++线程池

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

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

为什么需要线程池
目前的大多数网络服务器,包括Web服务器、Email服务器以及数据库服务器等都具有一个共同点,就是单位时间内必须处理数目巨大的连接请求,但处理时间却相对较短。
传 统多线程方案中我们采用的服务器模型则是一旦接受到请求之后,即创建一个新的线程,由该线程执行任务。任务执行完毕后,线程退出,这就是是“即时创建,即 时销毁”的策略。尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数极其频繁,那么服务器将处于 不停的创建线程,销毁线程的状态。
我们将传统方案中的线程执行过程分为三个过程:T1、T2、T3。

  1. T1:线程创建时间
  2. T2:线程执行时间,包括线程的同步等时间
  3.  T3:线程销毁时间

那么我们可以看出,线程本身的开销所占的比例为(T1+T3) / (T1+T2+T3)。如果线程执行的时间很短的话,这比开销可能占到20%-50%左右。如果任务执行时间很频繁的话,这笔开销将是不可忽略的。

 
除此之外,线程池能够减少创建的线程个数。通常线程池所允许的并发线程是有上界的,如果同时需要并发的线程数超过上界,那么一部分线程将会等待。而传统方案中,如果同时请求数目为2000,那么最坏情况下,系统可能需要产生2000个线程。尽管这不是一个很大的数目,但是也有部分机器可能达不到这种要求。
 
因此线程池的出现正是着眼于减少线程池本身带来的开销。线程池采用预创建的技术,在应用程序启动之后,将立即创建一定数量的线程(N1),放入空闲队列中。这些线程都是处于阻塞(Suspended)状态,不消耗CPU,但占用较小的内存空间。当任务到来后,缓冲池选择一个空闲线程,把任务传入此线程中运行。当N1个线程都在处理任务后,缓冲池自动创建一定数量的新线程,用于处理更多的任务。在任务执行完毕后线程也不退出,而是继续保持在池中等待下一次的任务。当系统比较空闲时,大部分线程都一直处于暂停状态,线程池自动销毁一部分线程,回收系统资源。
 
基于这种预创建技术,线程池将线程创建和销毁本身所带来的开销分摊到了各个具体的任务上,执行次数越多,每个任务所分担到的线程本身开销则越小,不过我们另外可能需要考虑进去线程之间同步所带来的开销

构建线程池框架
一般线程池都必须具备下面几个组成部分:

  • 线程池管理器:用于创建并管理线程池
  • 工作线程: 线程池中实际执行的线程
  • 任务接口: 尽管线程池大多数情况下是用来支持网络服务器,但是我们将线程执行的任务抽象出来,形成任务接口,从而是的线程池与具体的任务无关。
  • 任务队列: 线程池的概念具体到实现则可能是队列,链表之类的数据结构,其中保存执行线程。

我们实现的通用线程池框架由五个重要部分组成CThreadManage,CThreadPool,CThread,CJob,CWorkerThread,除此之外框架中还包括线程同步使用的类CThreadMutex和CCondition。

  • CJob是所有的任务的基类,其提供一个接口Run,所有的任务类都必须从该类继承,同时实现Run方法。该方法中实现具体的任务逻辑。
  • CThread是Linux中线程的包装,其封装了Linux线程最经常使用的属性和方法,它也是一个抽象类,是所有线程类的基类,具有一个接口Run。
  • CWorkerThread是实际被调度和执行的线程类,其从CThread继承而来,实现了CThread中的Run方法。
  • CThreadPool是线程池类,其负责保存线程,释放线程以及调度线程。
  • CThreadManage是线程池与用户的直接接口,其屏蔽了内部的具体实现。
  • CThreadMutex用于线程之间的互斥。
  • CCondition则是条件变量的封装,用于线程之间的同步。

CThreadManage直接跟客户端打交道,其接受需要创建的线程初始个数,并接受客户端提交的任务。这儿的任务是具体的非抽象的任务。CThreadManage的内部实际上调用的都是CThreadPool的相关操作。CThreadPool创建具体的线程,并把客户端提交的任务分发给CWorkerThread,CWorkerThread实际执行具体的任务。
 
理解系统组件

下面我们分开来了解系统中的各个组件。
CThreadManage
CThreadManage的功能非常简单,其提供最简单的方法,其类定义如下:


 
 
  1. class CThreadManage
  2. {
  3. private:
  4. CThreadPool* m_Pool;
  5. int m_NumOfThread;
  6. protected:
  7. public:
  8. CThreadManage();
  9. CThreadManage( int num);
  10. virtual ~CThreadManage();
  11. void SetParallelNum(int num);
  12. void Run(CJob* job,void* jobdata);
  13. void TerminateAll(void);
  14. };

其中m_Pool指向实际的线程池;m_NumOfThread是初始创建时候允许创建的并发的线程个数。另外Run和TerminateAll方法也非常简单,只是简单的调用CThreadPool的一些相关方法而已。其具体的实现如下:


 
 
  1. CThreadManage::CThreadManage()
  2. {
  3. m_NumOfThread = 10;
  4. m_Pool = new CThreadPool(m_NumOfThread);
  5. }
  6. CThreadManage::CThreadManage( int num)
  7. {
  8. m_NumOfThread = num;
  9. m_Pool = new CThreadPool(m_NumOfThread);
  10. }
  11. CThreadManage::~CThreadManage()
  12. {
  13. if( NULL != m_Pool)
  14. delete m_Pool;
  15. }
  16. void CThreadManage::SetParallelNum( int num)
  17. {
  18. m_NumOfThread = num;
  19. }
  20. void CThreadManage::Run(CJob* job, void* jobdata)
  21. {
  22. m_Pool->Run(job,jobdata);
  23. }
  24. void CThreadManage::TerminateAll( void)
  25. {
  26. m_Pool->TerminateAll();
  27. }

CThread
CThread 类实现了对Linux中线程操作的封装,它是所有线程的基类,也是一个抽象类,提供了一个抽象接口Run,所有的CThread都必须实现该Run方法。CThread的定义如下所示:


 
 
  1. class CThread
  2. {
  3. private:
  4. int m_ErrCode;
  5. Semaphore m_ThreadSemaphore; //the inner semaphore, which is used to realize
  6. unsigned long m_ThreadID;
  7. bool m_Detach; //The thread is detached
  8. bool m_CreateSuspended; //if suspend after creating
  9. char* m_ThreadName;
  10. ThreadState m_ThreadState; //the state of the thread
  11. protected:
  12. void SetErrcode(int errcode){m_ErrCode = errcode;}
  13. static void* ThreadFunction(void*);
  14. public:
  15. CThread();
  16. CThread( bool createsuspended, bool detach);
  17. virtual ~CThread();
  18. virtual void Run(void) = 0;
  19. void SetThreadState(ThreadState state){m_ThreadState = state;}
  20. bool Terminate(void); //Terminate the threa
  21. bool Start(void); //Start to execute the thread
  22. void Exit(void);
  23. bool Wakeup(void);
  24. ThreadState GetThreadState(void){ return m_ThreadState;}
  25. int GetLastError(void){ return m_ErrCode;}
  26. void SetThreadName(char* thrname){ strcpy(m_ThreadName,thrname);}
  27. char* GetThreadName(void){ return m_ThreadName;}
  28. int GetThreadID(void){ return m_ThreadID;}
  29. bool SetPriority(int priority);
  30. int GetPriority(void);
  31. int GetConcurrency(void);
  32. void SetConcurrency(int num);
  33. bool Detach(void);
  34. bool Join(void);
  35. bool Yield(void);
  36. int Self(void);
  37. };

线程的状态可以分为四种,空闲、忙碌、挂起、终止(包括正常退出和非正常退出)。由于目前Linux线程库不支持挂起操作,因此,我们的此处的挂起操作类似于暂停。如果线程创建后不想立即执行任务,那么我们可以将其“暂停”,如果需要运行,则唤醒。有一点必须注意的是,一旦线程开始执行任务,将不能被挂起,其将一直执行任务至完毕。
 
线程类的相关操作均十分简单。线程的执行入口是从Start()函数开始,其将调用函数ThreadFunction,ThreadFunction再调用实际的Run函数,执行实际的任务。
 
CThreadPool
CThreadPool是线程的承载容器,一般可以将其实现为堆栈、单向队列或者双向队列。在我们的系统中我们使用STL Vector对线程进行保存。CThreadPool的实现代码如下:


 
 
  1. class CThreadPool
  2. {
  3. friend class CWorkerThread;
  4. private:
  5. unsigned int m_MaxNum; //the max thread num that can create at the same time
  6. unsigned int m_AvailLow; //The min num of idle thread that shoule kept
  7. unsigned int m_AvailHigh; //The max num of idle thread that kept at the same time
  8. unsigned int m_AvailNum; //the normal thread num of idle num;
  9. unsigned int m_InitNum; //Normal thread num;
  10. protected:
  11. CWorkerThread* GetIdleThread(void);
  12. void AppendToIdleList(CWorkerThread* jobthread);
  13. void MoveToBusyList(CWorkerThread* idlethread);
  14. void MoveToIdleList(CWorkerThread* busythread);
  15. void DeleteIdleThread(int num);
  16. void CreateIdleThread(int num);
  17. public:
  18. CThreadMutex m_BusyMutex; //when visit busy list,use m_BusyMutex to lock and unlock
  19. CThreadMutex m_IdleMutex; //when visit idle list,use m_IdleMutex to lock and unlock
  20. CThreadMutex m_JobMutex; //when visit job list,use m_JobMutex to lock and unlock
  21. CThreadMutex m_VarMutex;
  22. CCondition m_BusyCond; //m_BusyCond is used to sync busy thread list
  23. CCondition m_IdleCond; //m_IdleCond is used to sync idle thread list
  24. CCondition m_IdleJobCond; //m_JobCond is used to sync job list
  25. CCondition m_MaxNumCond;
  26. vector<CWorkerThread*> m_ThreadList;
  27. vector<CWorkerThread*> m_BusyList; //Thread List
  28. vector<CWorkerThread*> m_IdleList; //Idle List
  29. CThreadPool();
  30. CThreadPool( int initnum);
  31. virtual ~CThreadPool();
  32. void SetMaxNum(int maxnum){m_MaxNum = maxnum;}
  33. int GetMaxNum(void){ return m_MaxNum;}
  34. void SetAvailLowNum(int minnum){m_AvailLow = minnum;}
  35. int GetAvailLowNum(void){ return m_AvailLow;}
  36. void SetAvailHighNum(int highnum){m_AvailHigh = highnum;}
  37. int GetAvailHighNum(void){ return m_AvailHigh;}
  38. int GetActualAvailNum(void){ return m_AvailNum;}
  39. int GetAllNum(void){ return m_ThreadList.size();}
  40. int GetBusyNum(void){ return m_BusyList.size();}
  41. void SetInitNum(int initnum){m_InitNum = initnum;}
  42. int GetInitNum(void){ return m_InitNum;}
  43. void TerminateAll(void);
  44. void Run(CJob* job,void* jobdata);
  45. };
  46. CWorkerThread* CThreadPool::GetIdleThread( void)
  47. {
  48. while(m_IdleList.size() == 0 )
  49. m_IdleCond.Wait();
  50. m_IdleMutex.Lock();
  51. if(m_IdleList.size() > 0 )
  52. {
  53. CWorkerThread* thr = (CWorkerThread*)m_IdleList.front();
  54. printf( "Get Idle thread %d\n",thr->GetThreadID());
  55. m_IdleMutex.Unlock();
  56. return thr;
  57. }
  58. m_IdleMutex.Unlock();
  59. return NULL;
  60. }
  61. //create num idle thread and put them to idlelist
  62. void CThreadPool::CreateIdleThread( int num)
  63. {
  64. for( int i= 0;i<num;i++){
  65. CWorkerThread* thr = new CWorkerThread();
  66. thr->SetThreadPool( this);
  67. AppendToIdleList(thr);
  68. m_VarMutex.Lock();
  69. m_AvailNum++;
  70. m_VarMutex.Unlock();
  71. thr->Start(); //begin the thread,the thread wait for job
  72. }
  73. }
  74. void CThreadPool::Run(CJob* job, void* jobdata)
  75. {
  76. assert(job!= NULL);
  77. //if the busy thread num adds to m_MaxNum,so we should wait
  78. if(GetBusyNum() == m_MaxNum)
  79. m_MaxNumCond.Wait();
  80. if(m_IdleList.size()<m_AvailLow)
  81. {
  82. if(GetAllNum()+m_InitNum-m_IdleList.size() < m_MaxNum )
  83. CreateIdleThread(m_InitNum-m_IdleList.size());
  84. else
  85. CreateIdleThread(m_MaxNum-GetAllNum());
  86. }
  87. CWorkerThread* idlethr = GetIdleThread();
  88. if(idlethr != NULL)
  89. {
  90. idlethr->m_WorkMutex.Lock();
  91. MoveToBusyList(idlethr);
  92. idlethr->SetThreadPool( this);
  93. job->SetWorkThread(idlethr);
  94. printf( "Job is set to thread %d \n",idlethr->GetThreadID());
  95. idlethr->SetJob(job,jobdata);
  96. }
  97. }

 
在CThreadPool中存在两个链表,一个是空闲链表,一个是忙碌链表。Idle链表中存放所有的空闲进程,当线程执行任务时候,其状态变为忙碌状态,同时从空闲链表中删除,并移至忙碌链表中。在CThreadPool的构造函数中,我们将执行下面的代码:


 
 
  1. for( int i= 0;i<m_InitNum;i++)
  2. {
  3. CWorkerThread* thr = new CWorkerThread();
  4. AppendToIdleList(thr);
  5. thr->SetThreadPool( this);
  6. thr->Start(); //begin the thread,the thread wait for job
  7. }


在该代码中,我们将创建m_InitNum个线程,创建之后即调用AppendToIdleList放入Idle链表中,由于目前没有任务分发给这些线程,因此线程执行Start后将自己挂起。
 
事实上,线程池中容纳的线程数目并不是一成不变的,其会根据执行负载进行自动伸缩。为此在CThreadPool中设定四个变量:

m_InitNum:处世创建时线程池中的线程的个数。

m_MaxNum:当前线程池中所允许并发存在的线程的最大数目。

m_AvailLow:当前线程池中所允许存在的空闲线程的最小数目,如果空闲数目低于该值,表明负载可能过重,此时有必要增加空闲线程池的数目。实现中我们总是将线程调整为m_InitNum个。

m_AvailHigh:当前线程池中所允许的空闲的线程的最大数目,如果空闲数目高于该值,表明当前负载可能较轻,此时将删除多余的空闲线程,删除后调整数也为m_InitNum个。

m_AvailNum:目前线程池中实际存在的线程的个数,其值介于m_AvailHigh和m_AvailLow之间。如果线程的个数始终维持在m_AvailLow和m_AvailHigh之间,则线程既不需要创建,也不需要删除,保持平衡状态。因此如何设定m_AvailLow和m_AvailHigh的值,使得线程池最大可能的保持平衡态,是线程池设计必须考虑的问题。
 
线程池在接受到新的任务之后,线程池首先要检查是否有足够的空闲池可用。检查分为三个步骤:
 
(1)检查当前处于忙碌状态的线程是否达到了设定的最大值m_MaxNum,如果达到了,表明目前没有空闲线程可用,而且也不能创建新的线程,因此必须等待直到有线程执行完毕返回到空闲队列中。
 
(2)如果当前的空闲线程数目小于我们设定的最小的空闲数目m_AvailLow,则我们必须创建新的线程,默认情况下,创建后的线程数目应该为m_InitNum,因此创建的线程数目应该为( 当前空闲线程数与m_InitNum);但是有一种特殊情况必须考虑,就是现有的线程总数加上创建后的线程数可能超过m_MaxNum,因此我们必须对线程的创建区别对待。


 
 
  1. if(GetAllNum()+m_InitNum-m_IdleList.size() < m_MaxNum )
  2. CreateIdleThread(m_InitNum-m_IdleList.size());
  3. else
  4. CreateIdleThread(m_MaxNum-GetAllNum());

如果创建后总数不超过m_MaxNum,则创建后的线程为m_InitNum;如果超过了,则只创建( m_MaxNum-当前线程总数 )个。
(3)调用GetIdleThread方法查找空闲线程。如果当前没有空闲线程,则挂起;否则将任务指派给该线程,同时将其移入忙碌队列。
当线程执行完毕后,其会调用MoveToIdleList方法移入空闲链表中,其中还调用m_IdleCond.Signal()方法,唤醒GetIdleThread()中可能阻塞的线程。
 
CJob
CJob类相对简单,其封装了任务的基本的属性和方法,其中最重要的是Run方法,代码如下:


 
 
  1. class CJob
  2. {
  3. private:
  4. int m_JobNo; //The num was assigned to the job
  5. char* m_JobName; //The job name
  6. CThread *m_pWorkThread; //The thread associated with the job
  7. public:
  8. CJob( void );
  9. virtual ~CJob();
  10. int GetJobNo(void) const { return m_JobNo; }
  11. void SetJobNo(int jobno){ m_JobNo = jobno;}
  12. char* GetJobName(void) const { return m_JobName; }
  13. void SetJobName(char* jobname);
  14. CThread *GetWorkThread(void){ return m_pWorkThread; }
  15. void SetWorkThread ( CThread *pWorkThread ){
  16. m_pWorkThread = pWorkThread;
  17. }
  18. virtual void Run ( void *ptr ) = 0;
  19. };

线程池使用示例
至此我们给出了一个简单的与具体任务无关的线程池框架。使用该框架非常的简单,我们所需要的做的就是派生CJob类,将需要完成的任务实现在Run方法中。然后将该Job交由CThreadManage去执行。下面我们给出一个简单的示例程序


 
 
  1. class CXJob: public CJob
  2. {
  3. public:
  4. CXJob(){i= 0;}
  5. ~CXJob(){}
  6. void Run(void* jobdata) {
  7. printf( "The Job comes from CXJOB\n");
  8. sleep( 2);
  9. }
  10. };
  11. class CYJob: public CJob
  12. {
  13. public:
  14. CYJob(){i= 0;}
  15. ~CYJob(){}
  16. void Run(void* jobdata) {
  17. printf( "The Job comes from CYJob\n");
  18. }
  19. };
  20. main()
  21. {
  22. CThreadManage* manage = new CThreadManage( 10);
  23. for( int i= 0;i< 40;i++)
  24. {
  25. CXJob* job = new CXJob();
  26. manage->Run(job, NULL);
  27. }
  28. sleep( 2);
  29. CYJob* job = new CYJob();
  30. manage->Run(job, NULL);
  31. manage->TerminateAll();
  32. }

CXJob和CYJob都是从Job类继承而来,其都实现了Run接口。CXJob只是简单的打印一句”The Job comes from CXJob”,CYJob也只打印”The Job comes from CYJob”,然后均休眠2秒钟。在主程序中我们初始创建10个工作线程。然后分别执行40次CXJob和一次CYJob。

C++ 线程池的封装实现
为了充分利用多核的优势,我们利用多线程来进行任务处理,但线程也同样不能滥用,会带来一下几个问题:
1)线程本身存在开销,系统必须为每个线程分配如栈,TLS(线程局部存储),寄存器等。
2)线程管理会给系统带来开销,context切换同样会给系统带来成本。
3)线程本身是可以重用的资源,不需要每次都进行初始化。

所以往往在使用中,我们无需把线程与task任务进行一对一对应,只需要预先初始化有限的线程个数来处理无限的task任务即可,线程池应运而生,原理也就是如此。

主要含有三个队列

  1. 工作队列
  2. 工作线程队列
  3. 忙碌线程队列

工作队列是一个阻塞队列,任务(仿函数)任务不算被push进来(notify阻塞获取的工作线程),工作线程队列(一直不变)则从该队列中获取任务执行(wait获取,当任务队列为空时阻塞等待通知),如果获取到任务,则将线程会进入忙碌线程队列中,执行任务的仿函数,当工作完成,重新移出工作线程队列。
定义线程池专属异常:


 
 
  1. struct TC_ThreadPool_Exception : public TC_Exception
  2. {
  3. TC_ThreadPool_Exception( const string &buffer) : TC_Exception(buffer){};
  4. TC_ThreadPool_Exception( const string &buffer, int err) : TC_Exception(buffer, err){};
  5. ~TC_ThreadPool_Exception () throw (){};
  6. };
  7. /**
  8. * @brief 用通线程池类, 与tc_functor, tc_functorwrapper配合使用.
  9. *
  10. * 使用方式说明:
  11. * 1 采用tc_functorwrapper封装一个调用
  12. * 2 用tc_threadpool对调用进行执行
  13. * 具体示例代码请参见:test/test_tc_thread_pool.cpp
  14. */
  15. /**线程池本身继承自锁,可以帮助锁定**/
  16. class TC_ThreadPool : public TC_ThreadLock
  17. {
  18. public:
  19. /**
  20. * @brief 构造函数
  21. *
  22. */
  23. TC_ThreadPool ();
  24. /**
  25. * @brief 析构, 会停止所有线程
  26. */
  27. ~TC_ThreadPool ();
  28. /**
  29. * @brief 初始化.
  30. *
  31. * @param num 工作线程个数
  32. */
  33. void init(size_t num);
  34. /**
  35. * @brief 获取线程个数.
  36. *
  37. * @return size_t 线程个数
  38. */
  39. size_t getThreadNum() { Lock sync(* this); return _jobthread. size(); }
  40. /**
  41. * @brief 获取线程池的任务数( exec添加进去的).
  42. *
  43. * @return size_t 线程池的任务数
  44. */
  45. size_t getJobNum() { return _jobqueue. size(); }
  46. /**
  47. * @brief 停止所有线程
  48. */
  49. void stop();
  50. /**
  51. * @brief 启动所有线程
  52. */
  53. void start();
  54. /**
  55. * @brief 启动所有线程并, 执行初始化对象.
  56. *
  57. * @param ParentFunctor
  58. * @param tf
  59. */
  60. template< class ParentFunctor>
  61. void start(const TC_FunctorWrapper< ParentFunctor> &tf)
  62. {
  63. for( size_t i = 0; i < _jobthread .size(); i++)
  64. {
  65. _startqueue. push_back( new TC_FunctorWrapper<ParentFunctor >(tf));
  66. }
  67. start();
  68. }
  69. /**
  70. * @brief 添加对象到线程池执行,该函数马上返回,
  71. * 线程池的线程执行对象
  72. */
  73. template< class ParentFunctor>
  74. void exec(const TC_FunctorWrapper< ParentFunctor> &tf)
  75. {
  76. _jobqueue.push_back( new TC_FunctorWrapper<ParentFunctor >(tf));
  77. }
  78. /**
  79. * @brief 等待所有工作全部结束(队列无任务, 无空闲线程).
  80. *
  81. * @param millsecond 等待的时间( ms), -1:永远等待
  82. * @return true, 所有工作都处理完毕
  83. * false,超时退出
  84. */
  85. bool waitForAllDone(int millsecond = -1);
  86. public:
  87. /**
  88. * @brief 线程数据基类,所有线程的私有数据继承于该类
  89. */
  90. class ThreadData
  91. {
  92. public:
  93. /**
  94. * @brief 构造
  95. */
  96. ThreadData(){};
  97. /**
  98. * @brief 析够
  99. */
  100. virtual ~ThreadData(){};
  101. /**
  102. * @brief 生成数据.
  103. *
  104. * @ param T
  105. * @return ThreadData*
  106. */
  107. template< typename T>
  108. static T* makeThreadData()
  109. {
  110. return new T;
  111. }
  112. };
  113. /**
  114. * @brief 设置线程数据.
  115. *
  116. * @param p 线程数据
  117. */
  118. static void setThreadData(ThreadData *p);
  119. /**
  120. * @brief 获取线程数据.
  121. *
  122. * @return ThreadData* 线程数据
  123. */
  124. static ThreadData* getThreadData();
  125. /**
  126. * @brief 设置线程数据, key需要自己维护.
  127. *
  128. * @param pkey 线程私有数据key
  129. * @param p 线程指针
  130. */
  131. static void setThreadData(pthread_key_t pkey, ThreadData *p);
  132. /**
  133. * @brief 获取线程数据, key需要自己维护.
  134. *
  135. * @param pkey 线程私有数据key
  136. * @return 指向线程的ThreadData*指针
  137. */
  138. static ThreadData* getThreadData(pthread_key_t pkey);
  139. protected:
  140. /**
  141. * @brief 释放资源.
  142. *
  143. * @param p
  144. */
  145. static void destructor(void *p);
  146. /**
  147. * @brief 初始化key
  148. */
  149. class KeyInitialize
  150. {
  151. public:
  152. /**
  153. * @brief 初始化key
  154. */
  155. KeyInitialize()
  156. {
  157. int ret = pthread_key_create(&TC_ThreadPool::g_key, TC_ThreadPool::destructor);
  158. if(ret != 0)
  159. {
  160. throw TC_ThreadPool_Exception( "[TC_ThreadPool::KeyInitialize] pthread_key_create error", ret);
  161. }
  162. }
  163. /**
  164. * @brief 释放key
  165. */
  166. ~KeyInitialize()
  167. {
  168. pthread_key_delete(TC_ThreadPool::g_key);
  169. }
  170. };
  171. /**
  172. * @brief 初始化key的控制
  173. */
  174. static KeyInitialize g_key_initialize;
  175. /**
  176. * @brief 数据key
  177. */
  178. static pthread_key_t g_key;
  179. protected:
  180. /**
  181. * @brief 线程池中的工作线程
  182. */
  183. class ThreadWorker : public TC_Thread
  184. {
  185. public:
  186. /**
  187. * @brief 工作线程构造函数.
  188. *
  189. * @ param tpool
  190. */
  191. ThreadWorker(TC_ThreadPool *tpool);
  192. /**
  193. * @brief 通知工作线程结束
  194. */
  195. void terminate();
  196. protected:
  197. /**
  198. * @brief 运行
  199. */
  200. virtual void run();
  201. protected:
  202. /**
  203. * 线程池指针
  204. */
  205. TC_ThreadPool * _tpool;
  206. /**
  207. * 是否结束线程
  208. */
  209. bool _bTerminate;
  210. };
  211. protected:
  212. /**
  213. * @brief 清除
  214. */
  215. void clear();
  216. /**
  217. * @brief 获取任务, 如果没有任务, 则为NULL.
  218. *
  219. * @return TC_FunctorWrapperInterface*
  220. */
  221. TC_FunctorWrapperInterface * get(ThreadWorker *ptw);
  222. /**
  223. * @brief 获取启动任务.
  224. *
  225. * @return TC_FunctorWrapperInterface*
  226. */
  227. TC_FunctorWrapperInterface * get();
  228. /**
  229. * @brief 空闲了一个线程.
  230. *
  231. * @param ptw
  232. */
  233. void idle(ThreadWorker *ptw);
  234. /**
  235. * @brief 通知等待在任务队列上的工作线程醒来
  236. */
  237. void notifyT();
  238. /**
  239. * @brief 是否处理结束.
  240. *
  241. * @return bool
  242. */
  243. bool finish();
  244. /**
  245. * @brief 线程退出时调用
  246. */
  247. void exit();
  248. friend class ThreadWorker;
  249. protected:
  250. /**
  251. * 任务队列
  252. */
  253. TC_ThreadQueue< TC_FunctorWrapperInterface*> _jobqueue;
  254. /**
  255. * 启动任务
  256. */
  257. TC_ThreadQueue< TC_FunctorWrapperInterface*> _startqueue;
  258. /**
  259. * 工作线程
  260. */
  261. std:: vector<ThreadWorker *> _jobthread;
  262. /**
  263. * 繁忙线程
  264. */
  265. std:: set<ThreadWorker *> _busthread;
  266. /**
  267. * 任务队列的锁
  268. */
  269. TC_ThreadLock _tmutex;
  270. /**
  271. * 是否所有任务都执行完毕
  272. */
  273. bool _bAllDone;
  274. };

工作线程设计如下:


 
 
  1. TC_ThreadPool ::ThreadWorker::ThreadWorker(TC_ThreadPool *tpool)
  2. : _tpool (tpool)
  3. , _bTerminate ( false)
  4. {
  5. }
  6. void TC_ThreadPool ::ThreadWorker::terminate()
  7. {
  8. _bTerminate = true;
  9. _tpool->notifyT();
  10. }
  11. void TC_ThreadPool ::ThreadWorker::run()
  12. {
  13. //调用初始化部分
  14. TC_FunctorWrapperInterface *pst = _tpool->get();
  15. if(pst)
  16. {
  17. try
  18. {
  19. (*pst)();
  20. }
  21. catch ( ... )
  22. {
  23. }
  24. delete pst;
  25. pst = NULL;
  26. }
  27. //调用处理部分
  28. while (! _bTerminate)
  29. {
  30. TC_FunctorWrapperInterface *pfw = _tpool->get( this);
  31. if(pfw != NULL)
  32. {
  33. auto_ptr< TC_FunctorWrapperInterface> apfw(pfw);
  34. try
  35. {
  36. (*pfw)();
  37. }
  38. catch ( ... )
  39. {
  40. }
  41. _tpool->idle( this);
  42. }
  43. }
  44. //结束
  45. _tpool-> exit();
  46. }
  47. 每个工作线程在刚开始时都会执行一下初始化操作,并进入一个无限循环的部分 //调用处理部分
  48. while (! _bTerminate)
  49. {
  50. TC_FunctorWrapperInterface *pfw = _tpool->get( this);
  51. if(pfw != NULL)
  52. {
  53. auto_ptr< TC_FunctorWrapperInterface> apfw(pfw);
  54. try
  55. {
  56. (*pfw)();
  57. }
  58. catch ( ... )
  59. {
  60. }
  61. _tpool->idle( this);
  62. }
  63. }

该工作主要是无限的从线程池的工作队列中获取任务并执行,如果成功获取任务,则会将线程移进忙碌队列:


 
 
  1. TC_FunctorWrapperInterface *TC_ThreadPool:: get(ThreadWorker *ptw)
  2. {
  3. TC_FunctorWrapperInterface *pFunctorWrapper = NULL;
  4. if(! _jobqueue. pop_front(pFunctorWrapper, 1000))
  5. {
  6. return NULL;
  7. }
  8. {
  9. Lock sync( _tmutex);
  10. _busthread. insert(ptw);
  11. }
  12. return pFunctorWrapper;
  13. }

执行完,移回工作线程队列:_tpool->idle( this);


 
 
  1. void TC_ThreadPool:: idle(ThreadWorker *ptw)
  2. {
  3. Lock sync( _tmutex);
  4. _busthread. erase(ptw);
  5. //无繁忙线程, 通知等待在线程池结束的线程醒过来
  6. if( _busthread. empty())
  7. {
  8. _bAllDone = true;
  9. _tmutex.notifyAll();
  10. }
  11. }


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

TC_ThreadPool:: idle中的


 
 
  1. if( _busthread. empty())
  2. {
  3. _bAllDone = true;
  4. _tmutex.notifyAll();
  5. }

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


 
 
  1. bool TC_ThreadPool:: waitForAllDone( int millsecond)
  2. {
  3. Lock sync( _tmutex);
  4. start1:
  5. //任务队列和繁忙线程都是空的
  6. if (finish())
  7. {
  8. return true;
  9. }
  10. //永远等待
  11. if(millsecond < 0)
  12. {
  13. _tmutex.timedWait( 1000);
  14. goto start1;
  15. }
  16. int64_t iNow = TC_Common:: now2ms();
  17. int m = millsecond;
  18. start2:
  19. bool b = _tmutex.timedWait(millsecond);
  20. //完成处理了
  21. if(finish())
  22. {
  23. return true;
  24. }
  25. if(!b)
  26. {
  27. return false;
  28. }
  29. millsecond = max(( int64_t ) 0, m - (TC_Common ::now2ms() - iNow));
  30. goto start2;
  31. return false;
  32. }
  33. _tmutex.timedWait(millsecond)方法唤醒。反复判断是否所有的工作是否完成:
  34. bool TC_ThreadPool:: finish()
  35. {
  36. return _startqueue. empty() && _jobqueue .empty() && _busthread. empty() && _bAllDone;
  37. }


整体cpp实现如下:


 
 
  1. TC_ThreadPool ::KeyInitialize TC_ThreadPool::g_key_initialize;
  2. pthread_key_t TC_ThreadPool::g_key ;
  3. void TC_ThreadPool::destructor( void *p)
  4. {
  5. ThreadData *ttd = ( ThreadData*)p;
  6. if(ttd)
  7. {
  8. delete ttd;
  9. }
  10. }
  11. void TC_ThreadPool:: exit()
  12. {
  13. TC_ThreadPool:: ThreadData *p = getThreadData();
  14. if(p)
  15. {
  16. delete p;
  17. int ret = pthread_setspecific( g_key, NULL );
  18. if(ret != 0)
  19. {
  20. throw TC_ThreadPool_Exception ( "[TC_ThreadPool::setThreadData] pthread_setspecific error", ret);
  21. }
  22. }
  23. _jobqueue. clear();
  24. }
  25. void TC_ThreadPool::setThreadData( TC_ThreadPool:: ThreadData *p)
  26. {
  27. TC_ThreadPool:: ThreadData *pOld = getThreadData();
  28. if(pOld != NULL && pOld != p)
  29. {
  30. delete pOld;
  31. }
  32. int ret = pthread_setspecific( g_key, ( void *)p);
  33. if(ret != 0)
  34. {
  35. throw TC_ThreadPool_Exception ( "[TC_ThreadPool::setThreadData] pthread_setspecific error", ret);
  36. }
  37. }
  38. TC_ThreadPool ::ThreadData * TC_ThreadPool::getThreadData ()
  39. {
  40. return ( ThreadData *) pthread_getspecific( g_key);
  41. }
  42. void TC_ThreadPool::setThreadData( pthread_key_t pkey, ThreadData *p)
  43. {
  44. TC_ThreadPool:: ThreadData *pOld = getThreadData(pkey);
  45. if(pOld != NULL && pOld != p)
  46. {
  47. delete pOld;
  48. }
  49. int ret = pthread_setspecific(pkey, ( void *)p);
  50. if(ret != 0)
  51. {
  52. throw TC_ThreadPool_Exception ( "[TC_ThreadPool::setThreadData] pthread_setspecific error", ret);
  53. }
  54. }
  55. TC_ThreadPool ::ThreadData * TC_ThreadPool::getThreadData( pthread_key_t pkey)
  56. {
  57. return ( ThreadData *) pthread_getspecific(pkey);
  58. }
  59. TC_ThreadPool::TC_ThreadPool()
  60. : _bAllDone ( true)
  61. {
  62. }
  63. TC_ThreadPool::~TC_ThreadPool()
  64. {
  65. stop();
  66. clear();
  67. }
  68. void TC_ThreadPool::clear()
  69. {
  70. std:: vector< ThreadWorker *>::iterator it = _jobthread. begin();
  71. while(it != _jobthread. end())
  72. {
  73. delete (*it);
  74. ++it;
  75. }
  76. _jobthread. clear();
  77. _busthread. clear();
  78. }
  79. void TC_ThreadPool::init( size_t num)
  80. {
  81. stop();
  82. Lock sync(* this);
  83. clear();
  84. for( size_t i = 0; i < num; i++)
  85. {
  86. _jobthread. push_back( new ThreadWorker( this));
  87. }
  88. }
  89. void TC_ThreadPool::stop()
  90. {
  91. Lock sync(* this);
  92. std:: vector< ThreadWorker *>::iterator it = _jobthread. begin();
  93. while(it != _jobthread. end())
  94. {
  95. if ((*it)-> isAlive())
  96. {
  97. (*it)-> terminate();
  98. (*it)-> getThreadControl().join ();
  99. }
  100. ++it;
  101. }
  102. _bAllDone = true;
  103. }
  104. void TC_ThreadPool::start()
  105. {
  106. Lock sync(* this);
  107. std:: vector< ThreadWorker *>::iterator it = _jobthread. begin();
  108. while(it != _jobthread. end())
  109. {
  110. (*it)-> start();
  111. ++it;
  112. }
  113. _bAllDone = false;
  114. }
  115. bool TC_ThreadPool:: finish()
  116. {
  117. return _startqueue. empty() && _jobqueue .empty() && _busthread. empty() && _bAllDone;
  118. }
  119. bool TC_ThreadPool::waitForAllDone( int millsecond)
  120. {
  121. Lock sync( _tmutex);
  122. start1:
  123. //任务队列和繁忙线程都是空的
  124. if (finish ())
  125. {
  126. return true;
  127. }
  128. //永远等待
  129. if(millsecond < 0)
  130. {
  131. _tmutex.timedWait( 1000);
  132. goto start1;
  133. }
  134. int64_t iNow = TC_Common:: now2ms();
  135. int m = millsecond;
  136. start2:
  137. bool b = _tmutex.timedWait(millsecond);
  138. //完成处理了
  139. if(finish ())
  140. {
  141. return true;
  142. }
  143. if(!b)
  144. {
  145. return false;
  146. }
  147. millsecond = max(( int64_t ) 0, m - (TC_Common ::now2ms() - iNow));
  148. goto start2;
  149. return false;
  150. }
  151. TC_FunctorWrapperInterface *TC_ThreadPool::get( ThreadWorker *ptw)
  152. {
  153. TC_FunctorWrapperInterface *pFunctorWrapper = NULL;
  154. if(! _jobqueue. pop_front(pFunctorWrapper, 1000))
  155. {
  156. return NULL;
  157. }
  158. {
  159. Lock sync( _tmutex);
  160. _busthread. insert(ptw);
  161. }
  162. return pFunctorWrapper;
  163. }
  164. TC_FunctorWrapperInterface *TC_ThreadPool::get()
  165. {
  166. TC_FunctorWrapperInterface *pFunctorWrapper = NULL;
  167. if(! _startqueue. pop_front(pFunctorWrapper))
  168. {
  169. return NULL;
  170. }
  171. return pFunctorWrapper;
  172. }
  173. void TC_ThreadPool::idle( ThreadWorker *ptw)
  174. {
  175. Lock sync( _tmutex);
  176. _busthread. erase(ptw);
  177. //无繁忙线程, 通知等待在线程池结束的线程醒过来
  178. if( _busthread. empty())
  179. {
  180. _bAllDone = true;
  181. _tmutex.notifyAll();
  182. }
  183. }
  184. void TC_ThreadPool::notifyT()
  185. {
  186. _jobqueue. notifyT();
  187. }

线程池使用后记
线程池适合场合
事 实上,线程池并不是万能的。它有其特定的使用场合。线程池致力于减少线程本身的开销对应用所产生的影响,这是有前提的,前提就是线程本身开销与线程执行任 务相比不可忽略。如果线程本身的开销相对于线程任务执行开销而言是可以忽略不计的,那么此时线程池所带来的好处是不明显的,比如对于FTP服务器以及Telnet服务器,通常传送文件的时间较长,开销较大,那么此时,我们采用线程池未必是理想的方法,我们可以选择“即时创建,即时销毁”的策略。
 总之线程池通常适合下面的几个场合:
 
(1)  单位时间内处理任务频繁而且任务处理时间短
 
(2)  对实时性要求较高。如果接受到任务后在创建线程,可能满足不了实时要求,因此必须采用线程池进行预创建。
 
(3)  必须经常面对高突发性事件,比如Web服务器,如果有足球转播,则服务器将产生巨大的冲击。此时如果采取传统方法,则必须不停的大量产生线程,销毁线程。此时采用动态线程池可以避免这种情况的发生。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值