ThreadPool.cc 1.2 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::Schedule(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