Lunchbox  1.16.0
Multi-threaded C++ toolbox library for all application developers creating high-performance multi-threaded programs.
threadPool.h
1 /* Copyright (c) 2016-2017, Mohamed-Ghaith Kaabi <mohamedghaith.kaabi@gmail.com>
2  *
3  * This library is free software; you can redistribute it and/or modify it under
4  * the terms of the GNU Lesser General Public License version 2.1 as published
5  * by the Free Software Foundation.
6  *
7  * This library is distributed in the hope that it will be useful, but WITHOUT
8  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
10  * details.
11  *
12  * You should have received a copy of the GNU Lesser General Public License
13  * along with this library; if not, write to the Free Software Foundation, Inc.,
14  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
15  */
16 
17 #ifndef LUNCHBOX_THREADPOOL_H
18 #define LUNCHBOX_THREADPOOL_H
19 
20 #include <condition_variable>
21 #include <functional>
22 #include <future>
23 #include <memory>
24 #include <queue>
25 #include <thread>
26 #include <vector>
27 
28 namespace lunchbox
29 {
38 {
39 public:
44  inline ThreadPool(
45  const size_t size = std::max(1u, std::thread::hardware_concurrency()));
50  inline ~ThreadPool();
51 
55  inline size_t getSize() const;
56 
61  template <typename F>
62  inline std::future<typename std::result_of<F()>::type> post(F&& f);
63 
68  template <typename F>
69  inline void postDetached(F&& f);
70 
74  inline bool hasPendingJobs() const;
75 
76 private:
77  inline void joinAll();
78  inline void work();
79 
80  std::vector<std::thread> _threads;
81  std::queue<std::function<void()> > _tasks;
82  mutable std::mutex _mutex;
83  std::condition_variable _condition;
84  bool _stop;
85 };
86 }
87 
88 #include "threadPool.ipp"
89 
90 #endif // LUNCHBOX_THREADPOOL_H
Thread pool for tasks execution.
Definition: threadPool.h:37
size_t getSize() const
Definition: threadPool.ipp:36
bool hasPendingJobs() const
Definition: threadPool.ipp:68
~ThreadPool()
Destroy this thread pool.
Definition: threadPool.ipp:26
std::future< typename std::result_of< F()>::type > post(F &&f)
Post a new task in the thread pool.
Definition: threadPool.ipp:42
ThreadPool(const size_t size=std::max(1u, std::thread::hardware_concurrency()))
Construct a ThreadPool.
Definition: threadPool.ipp:19
void postDetached(F &&f)
Post a detached task in the thread pool.
Definition: threadPool.ipp:59
Abstraction layer and common utilities for multi-threaded programming.
Definition: algorithm.h:29