GrPPI  0.3.1
Generic and Reusable Parallel Pattern Interface
worker_pool.h
Go to the documentation of this file.
1 
21 #ifndef GRPPI_NATIVE_WORKER_POOL_H
22 #define GRPPI_NATIVE_WORKER_POOL_H
23 
24 #include <thread>
25 
26 namespace grppi {
27 
34 class worker_pool {
35  public:
36 
41  worker_pool(int num_threads) noexcept : num_threads_{num_threads} {}
42 
47  ~worker_pool() noexcept { this->wait(); }
48 
49  worker_pool(worker_pool &&) noexcept = default;
50  worker_pool & operator=(worker_pool &&) noexcept = default;
51 
61  template <typename E, typename F, typename ... Args>
62  void launch(const E & ex, F f, Args && ... args) {
63  workers_.emplace_back([=,&ex]() {
64  auto manager = ex.thread_manager();
65  f(args...);
66  });
67  }
68 
69  template <typename E, typename F, typename ... Args>
70  void launch_tasks(const E & ex, F && f, Args && ... args) {
71  for (int i=0; i<num_threads_; ++i) {
72  workers_.emplace_back([=,&ex]() {
73  auto manager = ex.thread_manager();
74  f(args...);
75  });
76  }
77  }
78 
83  void wait() noexcept {
84  for (auto && w : workers_) { w.join(); }
85  workers_.clear();
86  }
87 
88  private:
89  const int num_threads_;
90  std::vector<std::thread> workers_;
91 };
92 
93 }
94 
95 #endif
Definition: callable_traits.h:26
void launch(const E &ex, F f, Args &&...args)
Launch a function in the pool.
Definition: worker_pool.h:62
void wait() noexcept
Wait until all launched tasks have been completed.
Definition: worker_pool.h:83
worker_pool & operator=(worker_pool &&) noexcept=default
Pool of worker threads. This class offers a simple pool of worker threads.
Definition: worker_pool.h:34
worker_pool(int num_threads) noexcept
Creates a worker pool with a number of threads.
Definition: worker_pool.h:41
void launch_tasks(const E &ex, F &&f, Args &&...args)
Definition: worker_pool.h:70
~worker_pool() noexcept
Destructs the worker pool after joining with all threads in the pool.
Definition: worker_pool.h:47