ThreadPool.cc 1.3 KB

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