thread_pool.cc 1.6 KB

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