ThreadPool.cc 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "Thread/ThreadPool.h"
  2. namespace Egametang {
  3. ThreadPool::ThreadPool(int num) :
  4. threadNum(num), running(true), workNum(0)
  5. {
  6. if (num == 0)
  7. {
  8. threadNum = boost::thread::hardware_concurrency();
  9. }
  10. for (int i = 0; i < threadNum; ++i)
  11. {
  12. ThreadPtr t(new boost::thread(
  13. boost::bind(&ThreadPool::Runner, this)));
  14. threads.push_back(t);
  15. t->detach();
  16. ++workNum;
  17. }
  18. }
  19. ThreadPool::~ThreadPool()
  20. {
  21. }
  22. void ThreadPool::Wait()
  23. {
  24. boost::mutex::scoped_lock lock(mutex);
  25. running = false;
  26. cond.notify_all();
  27. while (workNum > 0)
  28. {
  29. done.wait(lock);
  30. }
  31. }
  32. void ThreadPool::Runner()
  33. {
  34. bool continued = true;
  35. while (continued)
  36. {
  37. boost::function<void (void)> task;
  38. {
  39. boost::mutex::scoped_lock lock(mutex);
  40. while (running && tasks.empty())
  41. {
  42. cond.wait(lock);
  43. }
  44. if (!tasks.empty())
  45. {
  46. task = tasks.front();
  47. tasks.pop_front();
  48. }
  49. continued = running || !tasks.empty();
  50. }
  51. if (task)
  52. {
  53. task();
  54. }
  55. }
  56. if (--workNum == 0)
  57. {
  58. done.notify_one();
  59. }
  60. }
  61. bool ThreadPool::Schedule(boost::function<void (void)> task)
  62. {
  63. {
  64. boost::mutex::scoped_lock lock(mutex);
  65. if (!running)
  66. {
  67. return false;
  68. }
  69. tasks.push_back(task);
  70. }
  71. cond.notify_one();
  72. return true;
  73. }
  74. } // namespace Egametang