Tacopie  3.0.0
Tacopie is a TCP Client & Server C++11 library.
thread_pool.hpp
1 // MIT License
2 //
3 // Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com>
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in all
13 // copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 // SOFTWARE.
22 
23 #pragma once
24 
25 #include <atomic>
26 #include <condition_variable>
27 #include <functional>
28 #include <mutex>
29 #include <queue>
30 #include <thread>
31 #include <vector>
32 
33 namespace tacopie {
34 
35 namespace utils {
36 
40 class thread_pool {
41 public:
48  explicit thread_pool(std::size_t nb_threads);
49 
51  ~thread_pool(void);
52 
54  thread_pool(const thread_pool&) = delete;
56  thread_pool& operator=(const thread_pool&) = delete;
57 
58 public:
63  typedef std::function<void()> task_t;
64 
71  void add_task(const task_t& task);
72 
79  thread_pool& operator<<(const task_t& task);
80 
85  void stop(void);
86 
87 public:
91  bool is_running(void) const;
92 
93 public:
106  void set_nb_threads(std::size_t nb_threads);
107 
108 private:
112  void run(void);
113 
119  task_t fetch_task(void);
120 
124  bool should_stop(void) const;
125 
126 private:
130  std::vector<std::thread> m_workers;
131 
135  std::size_t m_nb_threads;
136 
140  std::atomic<bool> m_should_stop = ATOMIC_VAR_INIT(false);
141 
145  std::queue<task_t> m_tasks;
146 
150  std::mutex m_tasks_mtx;
151 
155  std::condition_variable m_tasks_condvar;
156 };
157 
158 } // namespace utils
159 
160 } // namespace tacopie
thread_pool(std::size_t nb_threads)
thread_pool & operator=(const thread_pool &)=delete
assignment operator
std::function< void()> task_t
Definition: thread_pool.hpp:63
Definition: io_service.hpp:48
void add_task(const task_t &task)
thread_pool & operator<<(const task_t &task)
void set_nb_threads(std::size_t nb_threads)
Definition: thread_pool.hpp:40
bool is_running(void) const