GrPPI  1.0
Generic and Reusable Parallel Pattern Interface
worker_pool.h
Go to the documentation of this file.
1 /*
2  * Copyright 2018 Universidad Carlos III de Madrid
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #ifndef GRPPI_NATIVE_WORKER_POOL_H
17 #define GRPPI_NATIVE_WORKER_POOL_H
18 
19 #include <thread>
20 
21 namespace grppi {
22 
29 class worker_pool {
30  public:
31 
36  worker_pool(int num_threads) noexcept :
37  num_threads_{num_threads},
38  workers_{}
39  {}
40 
45  ~worker_pool() noexcept { this->wait(); }
46 
47  worker_pool(worker_pool &&) noexcept = default;
48  worker_pool & operator=(worker_pool &&) noexcept = default;
49 
59  template <typename E, typename F, typename ... Args>
60  void launch(const E & ex, F f, Args && ... args) {
61  workers_.emplace_back([=,&ex]() {
62  auto manager = ex.thread_manager();
63  f(args...);
64  });
65  }
66 
67  template <typename E, typename F, typename ... Args>
68  void launch_tasks(const E & ex, F && f, Args && ... args) {
69  for (int i=0; i<num_threads_; ++i) {
70  workers_.emplace_back([=,&ex]() {
71  auto manager = ex.thread_manager();
72  f(args...);
73  });
74  }
75  }
76 
81  void wait() noexcept {
82  for (auto && w : workers_) { w.join(); }
83  workers_.clear();
84  }
85 
86  private:
87  const int num_threads_;
88  std::vector<std::thread> workers_;
89 };
90 
91 }
92 
93 #endif
Pool of worker threads. This class offers a simple pool of worker threads.
Definition: worker_pool.h:29
worker_pool(worker_pool &&) noexcept=default
void launch(const E &ex, F f, Args &&... args)
Launch a function in the pool.
Definition: worker_pool.h:60
void launch_tasks(const E &ex, F &&f, Args &&... args)
Definition: worker_pool.h:68
~worker_pool() noexcept
Destructs the worker pool after joining with all threads in the pool.
Definition: worker_pool.h:45
worker_pool(int num_threads) noexcept
Creates a worker pool with a number of threads.
Definition: worker_pool.h:36
void wait() noexcept
Wait until all launched tasks have been completed.
Definition: worker_pool.h:81
Definition: callable_traits.h:21