ThreadPoolExecutor.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #ifndef __THREAD_POOL_EXECUTOR__
  2. #define __THREAD_POOL_EXECUTOR__
  3. #include "thread.h"
  4. #include <set>
  5. #include <list>
  6. #include <windows.h>
  7. class CThreadPoolExecutor
  8. {
  9. public:
  10. CThreadPoolExecutor(void);
  11. ~CThreadPoolExecutor(void);
  12. private:
  13. static CThreadPoolExecutor* m_pThreadPoolExecutor;
  14. public:
  15. static CThreadPoolExecutor* GetInstance();
  16. static void FreeInstance();
  17. /**
  18. 初始化线程池,创建minThreads个线程
  19. **/
  20. bool Init(unsigned int minThreads, unsigned int maxThreads, unsigned int maxPendingTaskse);
  21. /**
  22. 执行任务,若当前任务列表没有满,将此任务插入到任务列表,返回true
  23. 若当前任务列表满了,但当前线程数量小于最大线程数,将创建新线程执行此任务,返回true
  24. 若当前任务列表满了,但当前线程数量等于最大线程数,将丢弃此任务,返回false
  25. **/
  26. bool Execute(Runnable * pRunnable);
  27. /**
  28. 终止线程池,先制止塞入任务,
  29. 然后等待直到任务列表为空,
  30. 然后设置最小线程数量为0,
  31. 等待直到线程数量为空,
  32. 清空垃圾堆中的任务
  33. **/
  34. void Terminate();
  35. /**
  36. 返回线程池中当前的线程数量
  37. **/
  38. unsigned int GetThreadPoolSize();
  39. private:
  40. /**
  41. 获取任务列表中的任务,若任务列表为空,返回NULL
  42. **/
  43. Runnable * GetTask();
  44. static unsigned int WINAPI StaticThreadFunc(void * arg);
  45. private:
  46. class CWorker : public CThread
  47. {
  48. public:
  49. CWorker(CThreadPoolExecutor * pThreadPool, Runnable * pFirstTask = NULL);
  50. ~CWorker();
  51. void Run();
  52. private:
  53. CThreadPoolExecutor * m_pThreadPool;
  54. Runnable * m_pFirstTask;
  55. volatile bool m_bRun;
  56. };
  57. typedef std::set<CWorker *> ThreadPool;
  58. typedef std::list<Runnable *> Tasks;
  59. typedef Tasks::iterator TasksItr;
  60. typedef ThreadPool::iterator ThreadPoolItr;
  61. ThreadPool m_ThreadPool;
  62. ThreadPool m_TrashThread;
  63. Tasks m_Tasks;
  64. CRITICAL_SECTION m_csTasksLock;
  65. CRITICAL_SECTION m_csThreadPoolLock;
  66. volatile bool m_bRun;
  67. volatile bool m_bEnableInsertTask;
  68. volatile unsigned int m_minThreads;
  69. volatile unsigned int m_maxThreads;
  70. volatile unsigned int m_maxPendingTasks;
  71. };
  72. #endif