ThreadPool.cc 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. running_ = true;
  33. }
  34. void ThreadPool::Runner()
  35. {
  36. bool continued = true;
  37. while (continued)
  38. {
  39. boost::function<void (void)> task;
  40. {
  41. boost::mutex::scoped_lock lock(mutex_);
  42. while (running_ && tasks_.empty())
  43. {
  44. cond_.wait(lock);
  45. }
  46. if (!tasks_.empty())
  47. {
  48. task = tasks_.front();
  49. tasks_.pop_front();
  50. }
  51. continued = running_ || !tasks_.empty();
  52. }
  53. if (task)
  54. {
  55. task();
  56. }
  57. }
  58. if (--work_num_ == 0)
  59. {
  60. done_.notify_one();
  61. }
  62. }
  63. bool ThreadPool::Schedule(boost::function<void (void)> task)
  64. {
  65. {
  66. boost::mutex::scoped_lock lock(mutex_);
  67. if (!running_)
  68. {
  69. return false;
  70. }
  71. tasks_.push_back(task);
  72. }
  73. cond_.notify_one();
  74. return true;
  75. }
  76. } // namespace Egametang