Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
q-consumer-threads.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
51# ifndef Q_CONSUMER_THREADS_H
52# define Q_CONSUMER_THREADS_H
53
54# include <thread>
55# include <condition_variable>
56# include <mutex>
57# include <atomic>
58# include <tpl_dynListQueue.H>
59# include <ah-errors.H>
60
68template <typename T>
69class [[deprecated("ConsumerQueueEvent goes in 8.0.0: use ThreadPool (thread_pool.H)")]]
71{
72 enum class Status { Ready, Executing };
73
74 std::atomic<Status> status = { Status::Ready };
75
76public:
77
79
88 virtual bool run() = 0;
89
91 virtual ~ConsumerQueueEvent() = default;
92};
93
100template <typename T>
101class [[deprecated("QueueTheadsPool goes in 8.0.0: use ThreadPool (thread_pool.H)")]]
103{
104public:
105
107 {
108 friend class QueueTheadsPool;
109
110 enum class Status { Ready, Executing };
111
112 Status status = Status::Ready;
113
114 protected:
115
116 std::atomic<size_t> count = 0;
117
118 public:
119
121
130 virtual void run() = 0;
131
132 size_t get_count() const noexcept { return count.load(); }
133
134 void increment_count() noexcept { ++count; }
135
137 };
138
140
141private:
142
143 std::mutex lck;
144 std::condition_variable cond;
146 size_t num_threads = 0;
147 size_t num_active = 0;
148 bool suspended = true;
149 bool shutting_down = false;
150 bool shutdown_done = false;
151 std::condition_variable shutdown_cv;
152
153 // The pool whose event the calling thread runs, if it runs one: its
154 // shutdown() cannot wait for the threads, its own among them
155 static inline thread_local const QueueTheadsPool * running_pool = nullptr;
156
158
159public:
160
165 {
166 shutdown();
167 }
168
169private:
170
171 static void handler(QueueTheadsPool<T> * threads_pool,
172 ConsumerQueueEvent * event)
173 {
174 threads_pool->run_event(event);
175 }
176
177 inline void run_event(ConsumerQueueEvent * event);
178
179public:
180
187 {
188 std::unique_lock<std::mutex> critical_section(lck);
189
190 // The event is checked before the thread starts: a thread that started
191 // with an event owned by another, which the pool did not count, left
192 // shutdown() waiting forever
193 ah_domain_error_if(event_list.exists([event] (auto e) { return e == event; }))
194 << "Thread creation with an event owned by another";
195
196 event_list.append(event);
197 ++num_threads;
198 try
199 {
200 // It waits for lck, held here, before it takes an item
201 std::thread(handler, this, event).detach();
202 }
203 catch (...)
204 {
205 --num_threads;
206 event_list.remove_ne([event] (auto e) { return e == event; });
207 throw;
208 }
209 }
210
211 bool put(T && item)
212 {
213 try
214 {
215 std::unique_lock<std::mutex> critical_section(lck);
216 if (num_threads == 0)
217 {
218 ah_domain_error_if(true) << "there is no any thread created";
219 }
220 q.put(std::forward<T>(item));
221 if (not suspended)
222 cond.notify_one(); // for waking up a thread
223 }
224 catch (...)
225 {
226 return false;
227 }
228
229 return true;
230 }
231
232 void resume()
233 {
234 std::unique_lock<std::mutex> critical_section(lck);
235 if (shutting_down)
236 return;
237
238 suspended = false;
239 cond.notify_all();
240 }
241
242 void suspend()
243 {
244 std::unique_lock<std::mutex> critical_section(lck);
245 if (shutting_down)
246 return;
247
248 suspended = true;
249 cond.notify_all();
250 }
251
253 {
254 std::unique_lock<std::mutex> critical_section(lck);
255 return suspended;
256 }
257
259 {
260 std::unique_lock<std::mutex> critical_section(lck);
261 return shutdown_done;
262 }
263
269 void shutdown()
270 {
271 std::unique_lock<std::mutex> critical_section(lck);
272 if (not shutting_down)
273 {
274 shutting_down = true;
275 cond.notify_all();
276 }
277
278 // An event that shut its pool down waited for its own thread, forever
279 if (running_pool == this)
280 return;
281
282 shutdown_cv.wait(critical_section, [this] { return num_threads == 0; } );
283 shutdown_done = true;
284 }
285};
286
287
288template <typename T>
290{
291 running_pool = this;
292 std::unique_lock<std::mutex> critical_section(lck);
293
294 while (true)
295 {
296 // The shutdown ends the wait also while suspended: shutdown() waited
297 // forever for the threads of a suspended pool, as one never resumed
298 cond.wait(critical_section,
299 [this] { return shutting_down or
300 (not suspended and not q.is_empty()); });
301
302 if (shutting_down)
303 break;
304
305 if (suspended or q.is_empty())
306 continue;
307
308 event->item = q.get();
309 ++num_active;
310 critical_section.unlock();
311
312 try
313 {
315 event->run();
316 event->status = ConsumerQueueEvent::Status::Ready;
317
318 critical_section.lock();
319 --num_active;
320 }
321 catch (...)
322 {
323 event->status = ConsumerQueueEvent::Status::Ready;
324 critical_section.lock();
325 --num_active;
326 }
327 }
328
329 running_pool = nullptr;
330 --num_threads;
331 shutdown_cv.notify_all();
332}
333
334
335# endif // Q_CONSUMER_THREADS_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T remove_ne() noexcept(std::is_nothrow_move_constructible_v< T >)
Remove the first item of the list, which must not be empty.
Definition htlist.H:1423
An event of a queue: what its derived classes do with each item.
virtual bool run()=0
this is a item extracted from the queue
virtual ~ConsumerQueueEvent()=default
Virtual, so that a derived event is destroyed through this class.
bool exists(Operation &op) const
Test for existence in the container of an element satisfying a criterion.
Definition ah-dry.H:1707
virtual void run()=0
this is a item extracted from the queue
Pool of consumer threads form a queue.
static thread_local const QueueTheadsPool * running_pool
~QueueTheadsPool()
Shut the pool down, as shutdown() does, if it was not, and wait for the events that are running: it t...
void shutdown()
Make the threads finish, also those of a suspended pool, and wait for them; again,...
std::condition_variable cond
DynList< ConsumerQueueEvent * > event_list
static void handler(QueueTheadsPool< T > *threads_pool, ConsumerQueueEvent *event)
std::condition_variable shutdown_cv
void run_event(ConsumerQueueEvent *event)
void create_thread(ConsumerQueueEvent *event)
Create a thread that consumes the items of the queue with event.
DynListQueue< T > q
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Dynamic queue implementation based on linked lists.