Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2014
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <thread_pool.hpp>
  2.  
  3. concurrency::thread_pool::thread_pool(int k) {
  4.     workers_count = k;
  5.     stop = false;
  6.  
  7.     start_workers();
  8. }
  9.  
  10. concurrency::thread_pool::~thread_pool() {
  11.     {
  12.         uniqueLock ul(mutex);
  13.         stop = true;
  14.     }
  15.  
  16.     cond.notify_all();
  17.  
  18.     for (int i = 0; i < workers_count; i++) {
  19.         workers[i].join();
  20.     }
  21. }
  22.  
  23. void concurrency::thread_pool::start_workers() {
  24.     for (int i = 0; i < workers_count; i++) {
  25.         //std::thread* t = new std::thread(concurrency::worker(*this));
  26.         //workers.push_back(t);
  27.  
  28.         workers.emplace_back([this]{
  29.             try {
  30.                 while (true) {
  31.                     std::function<void()> task(this->pop());
  32.  
  33.                     task();
  34.                 }
  35.             } catch (int n) {
  36.                 // worker should quit
  37.             }
  38.         });
  39.     }
  40. }
  41.  
  42. template<class F, class ...Args>
  43. void concurrency::thread_pool::push(F&& f, Args&&... args) {
  44.     if (stop) {
  45.         throw std::runtime_error("push on stopped thread_pool");
  46.     }
  47.  
  48.     std::function<void()> func = std::bind(f, args...);
  49.  
  50.     lockGuard l(mutex);
  51.  
  52.     bool should_wake = queue.empty();
  53.  
  54.     queue.push(func);
  55.  
  56.     if (should_wake) {
  57.         cond.notify_one();
  58.     }
  59. }
  60.  
  61. std::function<void()> concurrency::thread_pool::pop() {
  62.     uniqueLock u(mutex);
  63.  
  64.     while (!stop && queue.size() == 0) {
  65.         cond.wait(u);
  66.     }
  67.  
  68.     if (stop && queue.size() == 0) {
  69.         throw 1;
  70.     }
  71.  
  72.     std::function<void()> elm = queue.front();
  73.     queue.pop();
  74.  
  75.     return elm;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement