Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. #include "threadpool.h"
  2.  
  3. namespace dwt {
  4.  
  5. threadpool::threadpool(unsigned threads)
  6. : ready_(false), done_(false), joined_(false),
  7. tasks_(), threads_(), tasks_mtx_(), go_()
  8. {
  9. for (unsigned i = 0; i < threads; ++i)
  10. threads_.emplace_back(std::bind(&worker_thread_, this));
  11. }
  12.  
  13. threadpool::~threadpool()
  14. {
  15. if (!joined_)
  16. join_all();
  17. }
  18.  
  19. void threadpool::done()
  20. {
  21. std::unique_lock<std::mutex> lock(tasks_mtx_);
  22. done_ = true;
  23. }
  24.  
  25. void threadpool::join_all()
  26. {
  27. if (!done_)
  28. done();
  29. for (auto& t: threads_)
  30. t.join();
  31. joined_ = true;
  32. }
  33.  
  34. void threadpool::worker_thread_()
  35. {
  36. // wait for kickoff, if it hasn't happened yet
  37. {
  38. std::unique_lock<std::mutex> lock(tasks_mtx_);
  39. if (!ready_)
  40. go_.wait(lock);
  41. }
  42.  
  43. std::packaged_task<void()> current_task;
  44. while (true) {
  45. {
  46. std::unique_lock<std::mutex> lock(tasks_mtx_);
  47. if (!tasks_.empty()) {
  48. current_task = std::move(tasks_.front());
  49. tasks_.pop();
  50. } else /* tasks_ is empty */ if (done_) {
  51. break;
  52. } else /* empty, but not done: try again */ {
  53. continue;
  54. }
  55. }
  56. current_task();
  57. }
  58. }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement