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