thread_pool.cc 844 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "thread/thread_pool.h"
  2. namespace hainan
  3. {
  4. ThreadPool::ThreadPool(int32_t n):
  5. num(n), running(false)
  6. {
  7. }
  8. void ThreadPool::Start()
  9. {
  10. for(int i = 0; i < num; ++i)
  11. {
  12. boost::thread t(boost::function(&ThreadPool::Loop, boost::ref(this)));
  13. threads.push_back(t);
  14. t.detach();
  15. }
  16. running = true;
  17. }
  18. void ThreadPool::Stop()
  19. {
  20. running = false;
  21. cond.notify_all();
  22. }
  23. void ThreadPool::Loop()
  24. {
  25. while(running)
  26. {
  27. mutex.lock();
  28. while(tasks.empty())
  29. {
  30. cond.wait(mutex);
  31. }
  32. boost::function& t = tasks.front();
  33. tasks.pop_front();
  34. cond.notify_one();
  35. mutex.unlock();
  36. t();
  37. }
  38. }
  39. bool ThreadPool::PushTask(boost::function<void(void)> task)
  40. {
  41. boost::mutex::scoped_lock(&mutex);
  42. if(!running)
  43. {
  44. return false;
  45. }
  46. tasks.push_back(task);
  47. cond.notify_one();
  48. return true;
  49. }
  50. }