All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends Macros Pages
thread_pool.hpp
Go to the documentation of this file.
1 
8 #ifndef PAAL_THREAD_POOL_HPP
9 #define PAAL_THREAD_POOL_HPP
10 
11 #define BOOST_ERROR_CODE_HEADER_ONLY
12 #define BOOST_SYSTEM_NO_DEPRECATED
13 
14 #include <boost/asio/io_service.hpp>
15 
16 #include <cassert>
17 #include <cstdlib>
18 #include <thread>
19 #include <utility>
20 #include <vector>
21 
22 namespace paal {
23 
25 class thread_pool {
26  boost::asio::io_service m_io_service;
27  std::vector<std::thread> m_threadpool;
28  std::size_t m_threads_besides_current;
29 
30 public:
32  thread_pool(std::size_t size) : m_threads_besides_current(size - 1) {
33  assert(size > 0);
34  m_threadpool.reserve(m_threads_besides_current);
35  }
36 
38  template <typename Functor>
39  void post(Functor f) {
40  //TODO when there is only one thread in thread pool task could be run instantly
41  m_io_service.post(std::move(f));
42  }
43 
45  void run() {
46  auto io_run = [&](){m_io_service.run();};
47  for(std::size_t i = 0; i < m_threads_besides_current; ++i) {
48  m_threadpool.emplace_back(io_run);
49  }
50  // if threads_count == 1, we run all tasks in current thread
51  io_run();
52 
53  for (auto & thread : m_threadpool) thread.join();
54  }
55 };
56 
57 
58 }
59 
60 #endif /* PAAL_THREAD_POOL_HPP */
void post(Functor f)
post new task
Definition: thread_pool.hpp:39
simple threadpool, class uses also current thread!
Definition: thread_pool.hpp:25
void run()
run all posted tasks (blocking)
Definition: thread_pool.hpp:45
thread_pool(std::size_t size)
constructor
Definition: thread_pool.hpp:32