Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
worker_pool.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
78# ifndef WORKER_POOL_H
79# define WORKER_POOL_H
80
81# include <atomic>
82# include <cstdlib>
83# include <thread>
84# include <mutex>
85# include <condition_variable>
86# include <memory>
87
88# include <ah-errors.H>
89# include <tpl_arrayQueue.H>
90# include <iostream>
91
92using namespace Aleph;
93
118template <class WorkerFct>
119class [[deprecated("WorkersSet goes in 8.0.0: use ThreadPool (thread_pool.H)")]]
121{
122private:
123
124 WorkerFct worker_fct = nullptr;
125 size_t num_threads = 0;
126 size_t queue_capacity = 0;
127 mutable std::mutex m; // all the state below; mutable, for is_jobs_done()
128 std::condition_variable cond;
129
130 std::atomic<size_t> num_workers = 0;
131
134 bool shut_down = false;
135 bool job_done = false;
136
137 // Notified, with m, when the scheduled items are done or a worker
138 // returned true
139 std::condition_variable job_done_cond;
140
142 {
143 std::unique_lock<std::mutex> lock(m);
144 while (true)
145 {
146 cond.wait(lock, [this] { return num_workers > 0 or shut_down; });
147 if (shut_down)
148 return;
149
150 while (num_workers > 0)
151 {
152 cond.wait(lock, [this]
153 {
154 return (not q.is_empty()) or shut_down;
155 });
156
157 if (shut_down)
158 return;
159
160 if (not q.is_empty())
161 {
162 void * pars_ptr = q.get();
163
164 if (not job_done)
165 {
166 // The function runs without the lock; job_done is
167 // read and written only with it
168 lock.unlock();
169 bool done = false;
170 try
171 {
172 done = (*worker_fct)(pars_ptr);
173 }
174 catch (std::exception & e)
175 {
176 std::cout << "Warning: workers exception "
177 << e.what() << std::endl;
178 }
179 catch (...)
180 {
181 std::cout << "Warning: workers exception" << std::endl;
182 }
183 lock.lock();
184 if (done)
185 {
186 job_done = true;
187 job_done_cond.notify_all();
188 }
189 }
190 free(pars_ptr); // also an item that the function did not take
191 --num_workers;
192 }
193 }
194
195 job_done_cond.notify_all();
196 }
197 }
198
199public:
200
208 WorkersSet(WorkerFct worker_fct,
209 const size_t qsize, const size_t n = 16)
210 : worker_fct(worker_fct), num_threads(n), queue_capacity(qsize), q(qsize)
211 {
212 for (size_t i = 0; i < n; ++i)
213 threads.append(std::thread(&WorkersSet::worker_handler, this));
214 }
215
222 void shutdown()
223 {
224 std::unique_lock<std::mutex> lock(m);
225 shut_down = true;
226 cond.notify_all();
227 job_done_cond.notify_all();
228 }
229
233 {
234 shutdown();
235 threads.mutable_for_each([] (std::thread & th) { th.join(); });
236 while (not q.is_empty())
237 free(q.get());
238 }
239
245 void prepare_num_workers(size_t n)
246 {
247 std::unique_lock<std::mutex> lock(m);
248 num_workers = n;
249 // The items scheduled before wait for it: wake the workers
250 cond.notify_all();
251 }
252
267 void schedule_call(void * pars_ptr)
268 {
269 std::unique_lock<std::mutex> lock(m);
270 ah_overflow_error_if(q.size() >= queue_capacity)
271 << "WorkersSet::schedule_call(): the queue holds " << queue_capacity
272 << " items";
273 q.put(pars_ptr);
274 cond.notify_one();
275 }
276
282 bool is_jobs_done() const
283 {
284 std::unique_lock<std::mutex> lock(m);
285 return job_done;
286 }
287
297 {
298 // With a predicate: the items may be done before the wait starts, and
299 // a wakeup may be spurious. A shutdown ends it: the workers leave
300 // without the items, and it waited forever for them
301 std::unique_lock<std::mutex> lock(m);
302 job_done_cond.wait(lock, [this]
303 { return num_workers == 0 or job_done or shut_down; });
304 }
305};
306
307
308# endif
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Very simple queue implemented with a contiguous array.
T & put(const T &item) noexcept
Put an item into the queue by copy.
constexpr bool is_empty() const noexcept
Return true if the queue is empty.
T get() noexcept
Remove the oldest item of the queue.
constexpr size_t size() const noexcept
Return the number of items.
and Aleph::dry_detail::MutablyTraversable< typename Aleph::concepts_detail::defer< Container, Operation >::type, T > void mutable_for_each(Operation &operation)
Apply a mutable operation to each element of the container.
Definition ah-dry.H:1633
Thread pool for parallel worker function execution.
bool is_jobs_done() const
Check if a worker has signaled job completion.
std::condition_variable cond
void wait_until_all_workers_finished_or_job_is_done()
Block until all work items processed or job done signaled.
~WorkersSet()
Destructor shuts down and joins all worker threads, and frees the items that are still queued.
void shutdown()
Signal all workers to shut down.
void prepare_num_workers(size_t n)
Set the expected number of work items.
std::mutex m
std::condition_variable job_done_cond
FixedQueue< void * > q
void worker_handler()
DynList< std::thread > threads
void schedule_call(void *pars_ptr)
Schedule a work item for execution.
WorkersSet(WorkerFct worker_fct, const size_t qsize, const size_t n=16)
Construct worker pool with specified thread count.
Main namespace for Aleph-w library functions.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Circular queue implementations backed by arrays.