4#include <condition_variable> 
   35  explicit WorkerThreadPool(
size_t thread_count = std::thread::hardware_concurrency()) : stop(false)
 
   37    for (
size_t i = 0; i < thread_count; ++i)
 
   44            std::function<void()> task;
 
   46              std::unique_lock<std::mutex> lock(queue_mutex);
 
   47              condition.wait(lock, [
this] { 
return stop || !tasks.empty(); });
 
   49              if (stop && tasks.empty())
 
   52              task = std::move(tasks.front());
 
 
   78  template <
class F, 
class... Args>
 
   79  auto enqueue(F&& f, Args&&... args) -> std::future<
typename std::result_of<F(Args...)>::type>
 
   81    using return_type = 
typename std::result_of<F(Args...)>::type;
 
   83    auto task = std::make_shared<std::packaged_task<return_type()>>(
 
   84      std::bind(std::forward<F>(f), std::forward<Args>(args)...));
 
   86    std::future<return_type> result = task->get_future();
 
   88      std::unique_lock<std::mutex> lock(queue_mutex);
 
   93        throw std::runtime_error(
"Enqueue on stopped ThreadPool");
 
   96      tasks.emplace([task]() { (*task)(); });
 
   98    condition.notify_one();
 
 
  112      std::unique_lock<std::mutex> lock(queue_mutex);
 
  115    condition.notify_all();
 
  118    for (std::thread& worker : workers)
 
  120      if (worker.joinable())
 
 
  132  std::vector<std::thread>          workers; 
 
  133  std::queue<std::function<void()>> tasks;   
 
  135  std::mutex              queue_mutex; 
 
  136  std::condition_variable condition;   
 
  137  std::atomic<bool>       stop;        
 
 
WorkerThreadPool(size_t thread_count=std::thread::hardware_concurrency())
Constructs a worker thread pool with a specified number of threads.
Definition workers.hpp:35
 
WorkerThreadPool(const WorkerThreadPool &)=delete
 
~WorkerThreadPool()
Gracefully shuts down the thread pool.
Definition workers.hpp:109
 
auto operator=(const WorkerThreadPool &) -> WorkerThreadPool &=delete
 
auto enqueue(F &&f, Args &&... args) -> std::future< typename std::result_of< F(Args...)>::type >
Enqueues a task to be executed by the worker threads.
Definition workers.hpp:79