Helios++
Helios software for LiDAR simulations
ThreadPool.h
1 #pragma once
2 
3 
4 // Include boost ASIO preventing windows conflicts ---
5 #if defined(_WIN32) || defined(_WIN64) // If using windows
6 // Check WIN32 LEAN AND MEAN is specified, error otherwise
7 #ifndef WIN32_LEAN_AND_MEAN
8 #error WIN32 LEAN AND MEAN MACRO WAS NOT DEFINED
9 #endif
10 #include <SDKDDKVer.h>
11 #include <boost/asio.hpp>
12 
13 #else // If not using windows
14 #include <boost/asio.hpp>
15 
16 #endif
17 // --- Include boost ASIO preventing windows conflicts
18 #include <boost/thread.hpp>
19 #include <boost/function.hpp>
20 #include <logging.hpp>
21 #include <sstream>
22 
28 class ThreadPool{
29 protected:
30  // *** ATTRIBUTES *** //
31  // ******************** //
36  boost::asio::io_service io_service_;
42  boost::asio::executor_work_guard<boost::asio::io_service::executor_type>
47  std::size_t pool_size;
51  boost::thread_group threads_;
52 
53 public:
54  // *** CONSTRUCTION / DESTRUCTION *** //
55  // ************************************ //
60  explicit ThreadPool(std::size_t const _pool_size) :
61  work_(boost::asio::make_work_guard(io_service_)),
62  pool_size(_pool_size)
63  {
64  // Create threads
65  for (std::size_t i = 0; i < pool_size; ++i){
66  threads_.create_thread(
67  [&] () -> boost::asio::io_context::count_type{
68  return io_service_.run();
69  }
70  );
71  }
72  }
73 
74  virtual ~ThreadPool(){
75  // Force all threads to return from io_service::run().
76  io_service_.stop();
77 
78  // Suppress all exceptions.
79  try{
80  threads_.join_all();
81  }
82  catch (const std::exception&) {}
83  }
84 
85 public:
86  // *** M E T H O D S *** //
87  // *********************** //
93  virtual inline std::size_t getPoolSize() const {return pool_size;}
94 
95 
96 };
Base class providing core implementation of a thread pool to deal with multi threading tasks.
Definition: ThreadPool.h:28
std::size_t pool_size
Size of thread pool (number of threads)
Definition: ThreadPool.h:47
ThreadPool(std::size_t const _pool_size)
Thread pool constructor.
Definition: ThreadPool.h:60
boost::asio::io_service io_service_
Instance of boost input/output service for asynchronous data processing.
Definition: ThreadPool.h:36
boost::thread_group threads_
Group of threads.
Definition: ThreadPool.h:51
virtual std::size_t getPoolSize() const
Obtain the thread pool size.
Definition: ThreadPool.h:93
boost::asio::executor_work_guard< boost::asio::io_service::executor_type > work_
Instance of work guard to report the io service when it has pending tasks.
Definition: ThreadPool.h:43