ThreadPool.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <glog/logging.h>
  2. #include "Thread/ThreadPool.h"
  3. namespace Egametang {
  4. ThreadPool::ThreadPool(int num) :
  5. thread_num_(num), running_(false), work_num_(0)
  6. {
  7. if (num == 0)
  8. {
  9. thread_num_ = boost::thread::hardware_concurrency();
  10. }
  11. }
  12. ThreadPool::~ThreadPool()
  13. {
  14. }
  15. void ThreadPool::Start()
  16. {
  17. running_ = true;
  18. for (int i = 0; i < thread_num_; ++i)
  19. {
  20. ThreadPtr t(new boost::thread(
  21. boost::bind(&ThreadPool::Runner, this)));
  22. threads_.push_back(t);
  23. t->detach();
  24. ++work_num_;
  25. }
  26. }
  27. void ThreadPool::Stop()
  28. {
  29. VLOG(3)<< "Stop";
  30. boost::mutex::scoped_lock lock(mutex_);
  31. running_ = false;
  32. cond_.notify_all();
  33. while (work_num_ > 0)
  34. {
  35. VLOG(3) << "done tasks size = " << tasks_.size();
  36. done_.wait(lock);
  37. }
  38. }
  39. void ThreadPool::Runner()
  40. {
  41. VLOG(3) << "thread start";
  42. bool continued = true;
  43. while (continued)
  44. {
  45. boost::function<void (void)> task;
  46. {
  47. VLOG(3) << "loop lock";
  48. boost::mutex::scoped_lock lock(mutex_);
  49. VLOG(3) << "loop lock ok";
  50. while (running_ && tasks_.empty())
  51. {
  52. cond_.wait(lock);
  53. VLOG(3) << "cond";
  54. }
  55. if (!tasks_.empty())
  56. {
  57. VLOG(3) << "fetch task";
  58. task = tasks_.front();
  59. tasks_.pop_front();
  60. }
  61. continued = running_ || !tasks_.empty();
  62. VLOG(3) << "continued = " << continued
  63. << "running = " << running_
  64. << " tasks size = " << tasks_.size();
  65. VLOG(3) << "loop unlock";
  66. }
  67. if (task)
  68. {
  69. task();
  70. }
  71. }
  72. if (--work_num_ == 0)
  73. {
  74. VLOG(3) << "work_num = " << work_num_;
  75. done_.notify_one();
  76. }
  77. }
  78. bool ThreadPool::PushTask(boost::function<void (void)> task)
  79. {
  80. VLOG(3) << "push task";
  81. {
  82. boost::mutex::scoped_lock lock(mutex_);
  83. if (!running_)
  84. {
  85. return false;
  86. }
  87. tasks_.push_back(task);
  88. }
  89. VLOG(3) << "push task unlock";
  90. cond_.notify_one();
  91. return true;
  92. }
  93. } // namespace Egametang