ADTF  3.18.3
threadpool.h
1 /*
2 Copyright (c) 2012 Jakob Progsch, Václav Zeman
3 
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7 
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely, subject to the following restrictions:
11 
12  1. The origin of this software must not be misrepresented; you must not
13  claim that you wrote the original software. If you use this software
14  in a product, an acknowledgment in the product documentation would be
15  appreciated but is not required.
16 
17  2. Altered source versions must be plainly marked as such, and must not be
18  misrepresented as being the original software.
19 
20  3. This notice may not be removed or altered from any source
21 distribution.
22 */
23 
24 #ifndef THREAD_POOL_H
25 #define THREAD_POOL_H
26 
27 #include <vector>
28 #include <queue>
29 #include <memory>
30 #include <thread>
31 #include <mutex>
32 #include <condition_variable>
33 #include <future>
34 #include <functional>
35 #include <stdexcept>
36 
37 namespace jsonrpc {
38 class ThreadPool {
39 public:
40  ThreadPool(size_t);
41  template<class F, class... Args>
42  auto enqueue(F&& f, Args&&... args)
43  -> std::future<typename std::result_of<F(Args...)>::type>;
44  ~ThreadPool();
45 private:
46  // need to keep track of threads so we can join them
47  std::vector< std::thread > workers;
48  // the task queue
49  std::queue< std::function<void()> > tasks;
50 
51  // synchronization
52  std::mutex queue_mutex;
53  std::condition_variable condition;
54  bool stop;
55 };
56 
57 // the constructor just launches some amount of workers
58 inline ThreadPool::ThreadPool(size_t threads)
59  : stop(false)
60 {
61  for(size_t i = 0;i<threads;++i)
62  workers.emplace_back(
63  [this]
64  {
65  for(;;)
66  {
67  std::function<void()> task;
68 
69  {
70  std::unique_lock<std::mutex> lock(this->queue_mutex);
71  this->condition.wait(lock,
72  [this]{ return this->stop || !this->tasks.empty(); });
73  if(this->stop && this->tasks.empty())
74  return;
75  task = std::move(this->tasks.front());
76  this->tasks.pop();
77  }
78 
79  task();
80  }
81  }
82  );
83 }
84 
85 // add new work item to the pool
86 template<class F, class... Args>
87 auto ThreadPool::enqueue(F&& f, Args&&... args)
88  -> std::future<typename std::result_of<F(Args...)>::type>
89 {
90  using return_type = typename std::result_of<F(Args...)>::type;
91 
92  auto task = std::make_shared< std::packaged_task<return_type()> >(
93  std::bind(std::forward<F>(f), std::forward<Args>(args)...)
94  );
95 
96  std::future<return_type> res = task->get_future();
97  {
98  std::unique_lock<std::mutex> lock(queue_mutex);
99 
100  // don't allow enqueueing after stopping the pool
101  if(stop)
102  throw std::runtime_error("enqueue on stopped ThreadPool");
103 
104  tasks.emplace([task](){ (*task)(); });
105  }
106  condition.notify_one();
107  return res;
108 }
109 
110 // the destructor joins all threads
111 inline ThreadPool::~ThreadPool()
112 {
113  {
114  std::unique_lock<std::mutex> lock(queue_mutex);
115  stop = true;
116  }
117  condition.notify_all();
118  for(std::thread &worker: workers)
119  worker.join();
120 }
121 }
122 
123 
124 #endif