Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
thread_pool.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
109#ifndef ALEPH_THREAD_POOL_H
110#define ALEPH_THREAD_POOL_H
111
112#include <future>
113#include <queue>
114#include <functional>
115#include <algorithm>
116#include <condition_variable>
117#include <atomic>
118#include <vector>
119#include <list>
120#include <thread>
121#include <mutex>
122#include <stdexcept>
123#include <type_traits>
124#include <tuple>
125#include <memory>
126#include <limits>
127#include <optional>
128#include <chrono>
129#include <numeric>
130#include <iterator>
131#include <string>
132
133namespace Aleph
134{
141 class operation_canceled : public std::runtime_error
142 {
143 public:
145 : std::runtime_error("operation canceled") {}
146
147 explicit operation_canceled(const std::string & message)
148 : std::runtime_error(message) {}
149 };
150
152 class ThreadPool;
153
157 ThreadPool &default_pool();
158
161 {
162 std::atomic<bool> stop_requested{false};
163 std::mutex observer_mutex;
164 std::vector<std::condition_variable *> observers;
165
166 void register_condition_variable(std::condition_variable * cv)
167 {
168 std::lock_guard<std::mutex> lock(observer_mutex);
169 observers.push_back(cv);
170 }
171
172 void unregister_condition_variable(std::condition_variable * cv)
173 {
174 std::lock_guard<std::mutex> lock(observer_mutex);
175 auto it = std::find(observers.begin(), observers.end(), cv);
176 if (it != observers.end())
177 observers.erase(it);
178 }
179
180 // under the lock, so that unregistering waits for a notification in
181 // progress and the caller may then destroy its condition variable;
182 // notify_all() does not block
183 void notify_observers() noexcept
184 {
185 std::lock_guard<std::mutex> lock(observer_mutex);
186 for (auto * cv : observers)
187 if (cv != nullptr)
188 cv->notify_all();
189 }
190 };
191
192 namespace cancellation_detail
193 {
199 {
200 std::condition_variable * cv;
201 std::mutex * mutex;
202 size_t busy = 0;
203 bool removed = false;
204 };
205
219 {
221 std::list<Locked_Observer> locked_observers;
222
224 std::condition_variable not_busy;
225
232 std::list<Locked_Observer>::iterator
233 register_locked(std::condition_variable & cv, std::mutex & mutex)
234 {
235 std::lock_guard<std::mutex> lock(observer_mutex);
236 locked_observers.push_back(Locked_Observer{&cv, &mutex});
237 return std::prev(locked_observers.end());
238 }
239
243 void unregister_locked(const std::list<Locked_Observer>::iterator it) noexcept
244 {
245 std::unique_lock<std::mutex> lock(observer_mutex);
246 it->removed = true;
247 not_busy.wait(lock, [&] { return it->busy == 0; });
248 locked_observers.erase(it);
249 }
250
258 {
259 std::unique_lock<std::mutex> lock(observer_mutex);
260 for (auto it = locked_observers.begin(); ; )
261 {
262 while (it != locked_observers.end() and it->removed)
263 ++it;
264 if (it == locked_observers.end())
265 return;
266
267 ++it->busy; // so that it is not erased while unlocked
268 std::condition_variable * const cv = it->cv;
269 std::mutex * const mutex = it->mutex;
270 lock.unlock();
271 {
272 std::lock_guard<std::mutex> waiter_lock(*mutex);
273 }
274 cv->notify_all();
275 lock.lock();
276
277 const auto next = std::next(it);
278 if (--it->busy == 0 and it->removed)
279 not_busy.notify_all();
280 it = next;
281 }
282 }
283 };
284 } // namespace cancellation_detail
285
293 {
294 std::shared_ptr<cancellation_detail::Exact_State> state_;
295
296 explicit CancellationToken(std::shared_ptr<cancellation_detail::Exact_State> state) noexcept
297 : state_(std::move(state)) {}
298
299 friend class CancellationSource;
300
301 public:
312 {
313 std::shared_ptr<CancellationState> state_;
314 std::condition_variable *cv_ = nullptr;
315
316 // a registration made with a mutex
317 std::shared_ptr<cancellation_detail::Exact_State> locked_state_;
318 std::list<cancellation_detail::Locked_Observer>::iterator locked_{};
319
321 std::shared_ptr<cancellation_detail::Exact_State> state,
322 const std::list<cancellation_detail::Locked_Observer>::iterator it) noexcept
323 : locked_state_(std::move(state)), locked_(it) {}
324
325 friend class CancellationToken;
326
327 void unregister() noexcept
328 {
329 if (locked_state_ != nullptr)
330 locked_state_->unregister_locked(locked_);
331 else if (state_ != nullptr and cv_ != nullptr)
332 state_->unregister_condition_variable(cv_);
333 locked_state_ = nullptr;
334 locked_ = {};
335 cv_ = nullptr;
336 }
337
338 public:
341
346 ConditionVariableRegistration(std::shared_ptr<CancellationState> state,
347 std::condition_variable * cv) noexcept
348 : state_(std::move(state)), cv_(cv) {}
349
354 (const ConditionVariableRegistration &) = delete;
355
357 : state_(std::move(other.state_)), cv_(other.cv_),
358 locked_state_(std::move(other.locked_state_)), locked_(other.locked_)
359 {
360 other.cv_ = nullptr;
361 other.locked_ = {}; // invalid once the registration ends
362 }
363
365 (ConditionVariableRegistration && other) noexcept
366 {
367 if (this == &other)
368 return *this;
369 unregister();
370 state_ = std::move(other.state_);
371 cv_ = other.cv_;
372 other.cv_ = nullptr;
373 locked_state_ = std::move(other.locked_state_);
374 locked_ = other.locked_;
375 other.locked_ = {};
376 return *this;
377 }
378
383 };
384
386 CancellationToken() = default;
387
389 [[nodiscard]] bool stop_requested() const noexcept
390 {
391 return state_ != nullptr and state_->stop_requested.load(std::memory_order_relaxed);
392 }
393
395 [[nodiscard]] bool is_cancellation_requested() const noexcept
396 {
397 return stop_requested();
398 }
399
402 {
403 if (stop_requested())
404 throw operation_canceled();
405 }
406
408 [[nodiscard]] bool valid() const noexcept { return state_ != nullptr; }
409
424 [[nodiscard,
425 deprecated("use notify_on_cancel(cv, mutex), which cannot miss the notification")]]
426 ConditionVariableRegistration notify_on_cancel(std::condition_variable & cv) const
427 {
428 if (state_ == nullptr or stop_requested())
429 return {};
430 state_->register_condition_variable(&cv);
431 if (stop_requested())
432 {
433 state_->unregister_condition_variable(&cv);
434 cv.notify_all();
435 return {};
436 }
438 }
439
480 std::condition_variable & cv, std::mutex & mutex) const
481 {
482 if (state_ == nullptr or stop_requested())
483 return {};
484 return ConditionVariableRegistration(state_, state_->register_locked(cv, mutex));
485 }
486 };
487
496 {
497 std::shared_ptr<cancellation_detail::Exact_State> state_ =
498 std::make_shared<cancellation_detail::Exact_State>();
499
500 public:
503
505 [[nodiscard]] CancellationToken token() const noexcept
506 {
508 }
509
517 void request_cancel() noexcept
518 {
519 state_->stop_requested.store(true, std::memory_order_relaxed);
520 state_->notify_observers();
521 state_->notify_locked_observers();
522 }
523
525 void cancel() noexcept { request_cancel(); }
526
528 [[nodiscard]] bool stop_requested() const noexcept
529 {
530 return state_->stop_requested.load(std::memory_order_relaxed);
531 }
532
534 void reset() { state_ = std::make_shared<cancellation_detail::Exact_State>(); }
535 };
536
544 {
545 size_t min_size = 0;
546 size_t chunk_size = 0;
547 size_t max_tasks = 0;
548 ThreadPool *pool = nullptr;
550 };
551
557 class queue_overflow_error : public std::overflow_error
558 {
559 public:
561 : std::overflow_error("ThreadPool queue overflow: " +
562 std::to_string(current_size) + " >= hard_limit " +
565
567 [[nodiscard]] size_t current_size() const noexcept { return current_size_; }
568
570 [[nodiscard]] size_t hard_limit() const noexcept { return hard_limit_; }
571
572 private:
575 };
576
582 {
583 size_t tasks_completed = 0;
584 size_t tasks_failed = 0;
586 size_t current_active = 0;
587 size_t num_workers = 0;
588 size_t peak_queue_size = 0;
589
591 [[nodiscard]] size_t total_processed() const noexcept
592 {
594 }
595
597 [[nodiscard]] double queue_utilization(size_t soft_limit) const noexcept
598 {
599 if (soft_limit == 0 or soft_limit == std::numeric_limits<size_t>::max())
600 return 0.0;
601 return (100.0 * current_queue_size) / soft_limit;
602 }
603 };
604
606 using ExceptionCallback = std::function<void(std::exception_ptr)>;
607
630 {
632 struct TaskBase
633 {
635 virtual ~TaskBase() = default;
636
637 virtual void execute() = 0;
638 };
639
641 template <typename F>
642 struct Task : TaskBase
643 {
645
646 explicit Task(F && f) : func(std::move(f)) {}
647
648 void execute() override { func(); }
649 };
650
651 std::vector<std::thread> workers;
652 std::queue<std::unique_ptr<TaskBase>> tasks;
653 mutable std::mutex queue_mutex;
654 std::condition_variable condition;
655 std::condition_variable space_available;
656 std::condition_variable idle_condition;
657 std::atomic<bool> stop{false};
658 std::atomic<size_t> active_tasks{0};
659
660 // Queue limits for bounded enqueue
661 size_t soft_limit_ = std::numeric_limits<size_t>::max();
662 size_t hard_limit_ = std::numeric_limits<size_t>::max();
663
664 // Statistics
665 std::atomic<size_t> tasks_completed_{0};
666 std::atomic<size_t> tasks_failed_{0};
667 std::atomic<size_t> peak_queue_size_{0};
668
669 // Exception callback for detached tasks
671
674 {
675 while (true)
676 {
677 std::unique_ptr<TaskBase> task;
678 bool should_notify_space = false; {
679 std::unique_lock<std::mutex> lock(queue_mutex);
680 condition.wait(lock, [this]
681 {
682 return stop or not tasks.empty();
683 });
684
685 if (stop and tasks.empty())
686 return;
687
688 // Check if we should notify waiters after popping
689 should_notify_space = (tasks.size() == soft_limit_);
690
691 task = std::move(tasks.front());
692 tasks.pop();
693 ++active_tasks;
694 }
695
696 // Notify any blocked enqueuers that space is available
697 if (should_notify_space)
698 space_available.notify_all();
699
700 task->execute();
701
702 // Update stats and check for idle state
703 --active_tasks;
704
705 // Notify wait_all if we're now idle
706 {
707 std::unique_lock<std::mutex> lock(queue_mutex);
708 if (tasks.empty() and active_tasks == 0)
709 idle_condition.notify_all();
710 }
711 }
712 }
713
716 void start_workers(size_t n)
717 {
718 try
719 {
720 workers.reserve(n);
721 for (size_t i = 0; i < n; ++i)
722 workers.emplace_back(&ThreadPool::worker_loop, this);
723 }
724 catch (...)
725 {
726 stop_workers();
727 throw;
728 }
729 }
730
733 { {
734 std::unique_lock<std::mutex> lock(queue_mutex);
735 stop = true;
736 }
737 condition.notify_all();
738
739 for (auto & worker: workers)
740 if (worker.joinable())
741 worker.join();
742
743 workers.clear();
744 }
745
747 template <typename F, typename... Args>
748 static auto make_invocable(F && f, Args &&... args)
749 {
750 // Decay types to store copies/moves, not references
751 return [func = std::forward<F>(f),
752 args_tuple = std::make_tuple(std::forward<Args>(args)...)]() mutable
753 {
754 return std::apply([&func](auto &&... a)
755 {
756 return std::invoke(std::move(func), std::forward<decltype(a)>(a)...);
757 }, std::move(args_tuple));
758 };
759 }
760
761 public:
769 explicit ThreadPool(size_t n_threads = std::thread::hardware_concurrency())
770 {
771 if (n_threads == 0)
772 n_threads = 1; // Ensure at least one worker
773
774 start_workers(n_threads);
775 }
776
778 ThreadPool(const ThreadPool &) = delete;
779
781 ThreadPool &operator=(const ThreadPool &) = delete;
782
784 ThreadPool(ThreadPool &&) = delete;
785
788
794 {
795 stop_workers();
796 }
797
841 template <typename F, typename... Args>
842 [[nodiscard]] auto enqueue(F && f, Args &&... args)
843 -> std::future<std::invoke_result_t<F, Args...>>
844 {
845 using return_type = std::invoke_result_t<F, Args...>;
846
847 // Create the invocable that captures function and arguments
848 auto invocable = make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
849
850 // Wrap in packaged_task for future support
851 auto promise = std::make_shared<std::promise<return_type>>();
852 std::future<return_type> result = promise->get_future();
853
854 // Capture stats counter for task completion tracking
855 auto completed_counter = &tasks_completed_;
856
857 // Create the task that will execute and set the promise
858 auto task_func = [invocable = std::move(invocable), promise, completed_counter]() mutable
859 {
860 try
861 {
862 if constexpr (std::is_void_v<return_type>)
863 {
864 invocable();
865 promise->set_value();
866 }
867 else
868 {
869 promise->set_value(invocable());
870 }
871 ++(*completed_counter);
872 }
873 catch (...)
874 {
875 promise->set_exception(std::current_exception());
876 ++(*completed_counter); // Still counts as processed
877 }
878 }; {
879 std::unique_lock<std::mutex> lock(queue_mutex);
880
881 if (stop)
882 throw std::runtime_error("enqueue on stopped ThreadPool");
883
884 tasks.push(std::make_unique<Task<decltype(task_func)>>(std::move(task_func)));
885
886 // Update peak queue size
887 const size_t current_size = tasks.size();
888 size_t peak = peak_queue_size_.load();
889 while (current_size > peak and
890 not peak_queue_size_.compare_exchange_weak(peak, current_size));
891 }
892
893 condition.notify_one();
894 return result;
895 }
896
923 template <typename F, typename... Args>
924 void enqueue_detached(F && f, Args &&... args)
925 {
926 auto invocable = make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
927
928 // Capture stats and callback
929 auto completed_counter = &tasks_completed_;
930 auto failed_counter = &tasks_failed_;
931 ExceptionCallback callback; {
932 std::unique_lock<std::mutex> lock(queue_mutex);
933 callback = exception_callback_;
934 }
935
936 auto task_func = [invocable = std::move(invocable),
937 completed_counter, failed_counter,
938 callback = std::move(callback)]() mutable
939 {
940 try
941 {
942 invocable();
943 ++(*completed_counter);
944 }
945 catch (...)
946 {
947 ++(*failed_counter);
948 // Call exception callback if set
949 if (callback)
950 {
951 try { callback(std::current_exception()); }
952 catch (...) { /* Ignore callback exceptions */ }
953 }
954 }
955 }; {
956 std::unique_lock<std::mutex> lock(queue_mutex);
957
958 if (stop)
959 throw std::runtime_error("enqueue_detached on stopped ThreadPool");
960
961 tasks.push(std::make_unique<Task<decltype(task_func)>>(std::move(task_func)));
962
963 // Update peak queue size
964 const size_t current_size = tasks.size();
965 size_t peak = peak_queue_size_.load();
966 while (current_size > peak and
967 not peak_queue_size_.compare_exchange_weak(peak, current_size));
968 }
969
970 condition.notify_one();
971 }
972
993 template <typename F, typename Container>
994 [[nodiscard]] auto enqueue_bulk(F && f, const Container & args_container)
995 -> std::vector<std::future<std::invoke_result_t<F, typename Container::value_type>>>
996 {
997 using return_type = std::invoke_result_t<F, typename Container::value_type>;
998 std::vector<std::future<return_type>> results;
999 results.reserve(args_container.size());
1000
1001 for (const auto & arg: args_container)
1002 results.push_back(enqueue(f, arg));
1003
1004 return results;
1005 }
1006
1028 void set_queue_limits(const size_t soft_limit,
1029 const size_t hard_limit = std::numeric_limits<size_t>::max())
1030 {
1031 std::unique_lock<std::mutex> lock(queue_mutex);
1032 soft_limit_ = soft_limit;
1033 hard_limit_ = (hard_limit == std::numeric_limits<size_t>::max() and
1034 soft_limit != std::numeric_limits<size_t>::max()) ?
1035 soft_limit * 10 // Default hard = 10x soft
1036 :
1037 hard_limit;
1038 }
1039
1044 [[nodiscard]] std::pair<size_t, size_t> get_queue_limits() const
1045 {
1046 std::unique_lock<std::mutex> lock(queue_mutex);
1047 return {soft_limit_, hard_limit_};
1048 }
1049
1084 template <typename F, typename... Args>
1085 [[nodiscard]] auto enqueue_bounded(F && f, Args &&... args)
1086 -> std::future<std::invoke_result_t<F, Args...>>
1087 {
1088 using return_type = std::invoke_result_t<F, Args...>;
1089
1090 auto invocable = make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
1091
1092 auto promise = std::make_shared<std::promise<return_type>>();
1093 std::future<return_type> result = promise->get_future();
1094
1095 auto task_func = [invocable = std::move(invocable), promise]() mutable
1096 {
1097 try
1098 {
1099 if constexpr (std::is_void_v<return_type>)
1100 {
1101 invocable();
1102 promise->set_value();
1103 }
1104 else
1105 {
1106 promise->set_value(invocable());
1107 }
1108 }
1109 catch (...)
1110 {
1111 promise->set_exception(std::current_exception());
1112 }
1113 }; {
1114 std::unique_lock<std::mutex> lock(queue_mutex);
1115
1116 // Check hard limit first (throws immediately)
1117 if (tasks.size() >= hard_limit_)
1118 throw queue_overflow_error(tasks.size(), hard_limit_);
1119
1120 // Block if at soft limit (wait for space)
1121 space_available.wait(lock, [this]
1122 {
1123 return stop or tasks.size() < soft_limit_;
1124 });
1125
1126 if (stop)
1127 throw std::runtime_error("enqueue_bounded on stopped ThreadPool");
1128
1129 // Re-check hard limit after waking up
1130 if (tasks.size() >= hard_limit_)
1131 throw queue_overflow_error(tasks.size(), hard_limit_);
1132
1133 tasks.push(std::make_unique<Task<decltype(task_func)>>(std::move(task_func)));
1134 }
1135
1136 condition.notify_one();
1137 return result;
1138 }
1139
1154 template <typename F, typename... Args>
1155 void enqueue_bounded_detached(F && f, Args &&... args)
1156 {
1157 auto invocable = make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
1158
1159 auto task_func = [invocable = std::move(invocable)]() mutable
1160 {
1161 try
1162 {
1163 invocable();
1164 }
1165 catch (...)
1166 {
1167 // Silently ignore exceptions in detached tasks
1168 }
1169 }; {
1170 std::unique_lock<std::mutex> lock(queue_mutex);
1171
1172 // Check hard limit first
1173 if (tasks.size() >= hard_limit_)
1174 throw queue_overflow_error(tasks.size(), hard_limit_);
1175
1176 // Block if at soft limit
1177 space_available.wait(lock, [this]
1178 {
1179 return stop or tasks.size() < soft_limit_;
1180 });
1181
1182 if (stop)
1183 throw std::runtime_error("enqueue_bounded_detached on stopped ThreadPool");
1184
1185 // Re-check hard limit after waking up
1186 if (tasks.size() >= hard_limit_)
1187 throw queue_overflow_error(tasks.size(), hard_limit_);
1188
1189 tasks.push(std::make_unique<Task<decltype(task_func)>>(std::move(task_func)));
1190 }
1191
1192 condition.notify_one();
1193 }
1194
1229 template <typename F, typename... Args>
1230 [[nodiscard]] auto try_enqueue(F && f, Args &&... args)
1231 -> std::optional<std::future<std::invoke_result_t<F, Args...>>>
1232 { {
1233 std::unique_lock<std::mutex> lock(queue_mutex);
1234
1235 if (stop)
1236 throw std::runtime_error("try_enqueue on stopped ThreadPool");
1237
1238 // Check if queue is at or above soft limit
1239 if (tasks.size() >= soft_limit_)
1240 return std::nullopt;
1241 }
1242
1243 // Queue has space, delegate to regular enqueue
1244 return enqueue(std::forward<F>(f), std::forward<Args>(args)...);
1245 }
1246
1269 template <typename F, typename... Args>
1270 bool try_enqueue_detached(F && f, Args &&... args)
1271 { {
1272 std::unique_lock<std::mutex> lock(queue_mutex);
1273
1274 if (stop)
1275 throw std::runtime_error("try_enqueue_detached on stopped ThreadPool");
1276
1277 if (tasks.size() >= soft_limit_)
1278 return false;
1279 }
1280
1281 enqueue_detached(std::forward<F>(f), std::forward<Args>(args)...);
1282 return true;
1283 }
1284
1288 [[nodiscard]] size_t num_threads() const noexcept
1289 {
1290 return workers.size();
1291 }
1292
1296 [[nodiscard]] size_t pending_tasks() const
1297 {
1298 std::unique_lock<std::mutex> lock(queue_mutex);
1299 return tasks.size();
1300 }
1301
1305 [[nodiscard]] size_t running_tasks() const noexcept
1306 {
1307 return active_tasks.load();
1308 }
1309
1313 [[nodiscard]] bool is_idle() const
1314 {
1315 std::unique_lock<std::mutex> lock(queue_mutex);
1316 return tasks.empty() and active_tasks == 0;
1317 }
1318
1322 [[nodiscard]] bool is_stopped() const noexcept
1323 {
1324 return stop.load();
1325 }
1326
1338 { {
1339 std::unique_lock<std::mutex> lock(queue_mutex);
1340 if (stop.exchange(true))
1341 return; // Already stopped
1342 }
1343 condition.notify_all();
1344
1345 for (auto & worker: workers)
1346 if (worker.joinable())
1347 worker.join();
1348
1349 workers.clear();
1350 }
1351
1368 void resize(size_t new_size)
1369 {
1370 if (new_size == 0)
1371 new_size = 1;
1372
1373 if (new_size == workers.size())
1374 return;
1375
1376 if (stop)
1377 throw std::runtime_error("cannot resize a stopped ThreadPool");
1378
1379 // Stop current workers (but don't clear tasks)
1380 {
1381 std::unique_lock<std::mutex> lock(queue_mutex);
1382 stop = true;
1383 }
1384 condition.notify_all();
1385
1386 for (auto & worker: workers)
1387 if (worker.joinable())
1388 worker.join();
1389
1390 workers.clear();
1391
1392 // Restart with new size
1393 stop = false;
1394 start_workers(new_size);
1395 }
1396
1404 void wait_all(const std::chrono::milliseconds poll_interval = std::chrono::milliseconds(1))
1405 {
1406 while (not is_idle())
1407 std::this_thread::sleep_for(poll_interval);
1408 }
1409
1419 template <typename Rep, typename Period>
1420 [[nodiscard]] bool wait_all_for(std::chrono::duration<Rep, Period> timeout)
1421 {
1422 std::unique_lock<std::mutex> lock(queue_mutex);
1423 return idle_condition.wait_for(lock, timeout, [this]
1424 {
1425 return tasks.empty() and active_tasks == 0;
1426 });
1427 }
1428
1438 template <typename Clock, typename Duration>
1439 [[nodiscard]] bool wait_all_until(std::chrono::time_point<Clock, Duration> deadline)
1440 {
1441 std::unique_lock<std::mutex> lock(queue_mutex);
1442 return idle_condition.wait_until(lock, deadline, [this]
1443 {
1444 return tasks.empty() and active_tasks == 0;
1445 });
1446 }
1447
1454 [[nodiscard]] ThreadPoolStats get_stats() const
1455 {
1456 ThreadPoolStats stats;
1457 stats.tasks_completed = tasks_completed_.load();
1458 stats.tasks_failed = tasks_failed_.load();
1459 stats.current_active = active_tasks.load();
1460 stats.num_workers = workers.size();
1461 stats.peak_queue_size = peak_queue_size_.load(); {
1462 std::unique_lock<std::mutex> lock(queue_mutex);
1463 stats.current_queue_size = tasks.size();
1464 }
1465
1466 return stats;
1467 }
1468
1472 {
1473 tasks_completed_ = 0;
1474 tasks_failed_ = 0;
1475 peak_queue_size_ = 0;
1476 }
1477
1500 {
1501 std::unique_lock<std::mutex> lock(queue_mutex);
1502 exception_callback_ = std::move(callback);
1503 }
1504
1527 template <typename F, typename Container>
1528 [[nodiscard]] auto enqueue_batch(F && f, const Container & args_list)
1529 -> std::vector<std::future<decltype(std::apply(f, *std::begin(args_list)))>>
1530 {
1531 using ArgsTuple = typename Container::value_type;
1532 using return_type = decltype(std::apply(f, std::declval<ArgsTuple>()));
1533
1534 std::vector<std::future<return_type>> results;
1535 results.reserve(std::distance(std::begin(args_list), std::end(args_list)));
1536
1537 std::vector<std::unique_ptr<TaskBase>> batch_tasks;
1538 batch_tasks.reserve(results.capacity());
1539
1540 // Capture stats counter
1541 auto completed_counter = &tasks_completed_;
1542
1543 for (const auto & args: args_list)
1544 {
1545 auto promise = std::make_shared<std::promise<return_type>>();
1546 results.push_back(promise->get_future());
1547
1548 auto task_func = [func = f, args, promise, completed_counter]() mutable
1549 {
1550 try
1551 {
1552 if constexpr (std::is_void_v<return_type>)
1553 {
1554 std::apply(func, args);
1555 promise->set_value();
1556 }
1557 else
1558 {
1559 promise->set_value(std::apply(func, args));
1560 }
1561 ++(*completed_counter);
1562 }
1563 catch (...)
1564 {
1565 promise->set_exception(std::current_exception());
1566 ++(*completed_counter);
1567 }
1568 };
1569
1570 batch_tasks.push_back(
1571 std::make_unique<Task<decltype(task_func)>>(std::move(task_func)));
1572 } {
1573 std::unique_lock<std::mutex> lock(queue_mutex);
1574
1575 if (stop)
1576 throw std::runtime_error("enqueue_batch on stopped ThreadPool");
1577
1578 for (auto & task: batch_tasks)
1579 tasks.push(std::move(task));
1580
1581 // Update peak queue size
1582 const size_t current_size = tasks.size();
1583 size_t peak = peak_queue_size_.load();
1584 while (current_size > peak and
1585 not peak_queue_size_.compare_exchange_weak(peak, current_size));
1586 }
1587
1588 // Notify all workers for batch
1589 condition.notify_all();
1590
1591 return results;
1592 }
1593 };
1594
1595 // =============================================================================
1596 // Parallel Algorithms
1597 // =============================================================================
1598
1599 namespace parallel_detail
1600 {
1602 {
1603 return options.pool == nullptr ? default_pool() : *options.pool;
1604 }
1605
1606 inline size_t resolve_chunk_size(const size_t total,
1607 const size_t num_threads,
1608 const ParallelOptions & options,
1609 const size_t min_chunk = 1)
1610 {
1611 if (total == 0)
1612 return 1;
1613
1614 size_t chunk_size = options.chunk_size;
1615 if (chunk_size == 0)
1616 chunk_size = std::max(min_chunk,
1617 total / std::max<size_t>(1, num_threads * 4));
1618
1619 if (options.max_tasks > 0)
1620 {
1621 const size_t min_for_cap =
1622 (total + options.max_tasks - 1) / options.max_tasks;
1623 chunk_size = std::max(chunk_size, std::max(min_chunk, min_for_cap));
1624 }
1625
1626 return std::max<size_t>(1, chunk_size);
1627 }
1628
1629 inline bool use_sequential_path(const size_t total,
1630 const ThreadPool & pool,
1631 const ParallelOptions & options) noexcept
1632 {
1633 if (total == 0)
1634 return true;
1635
1636 if (options.cancel_token.stop_requested())
1637 return true;
1638
1639 if (options.max_tasks == 1)
1640 return true;
1641
1642 if (options.min_size > 0 and total < options.min_size)
1643 return true;
1644
1645 return pool.num_threads() <= 1;
1646 }
1647
1648 inline void throw_if_canceled(const CancellationToken & token)
1649 {
1651 }
1652
1653 template <typename InputIt1, typename InputIt2, typename OutputIt, typename Compare>
1654 void merge_sequential(InputIt1 first1, InputIt1 last1,
1655 InputIt2 first2, InputIt2 last2,
1656 OutputIt d_first, Compare comp,
1657 const CancellationToken & token)
1658 {
1659 while (first1 != last1 and first2 != last2)
1660 {
1661 throw_if_canceled(token);
1662 if (comp(*first2, *first1))
1663 *d_first++ = *first2++;
1664 else
1665 *d_first++ = *first1++;
1666 }
1667
1668 while (first1 != last1)
1669 {
1670 throw_if_canceled(token);
1671 *d_first++ = *first1++;
1672 }
1673
1674 while (first2 != last2)
1675 {
1676 throw_if_canceled(token);
1677 *d_first++ = *first2++;
1678 }
1679 }
1680 } // namespace parallel_detail
1681
1713 template <typename Iterator, typename F>
1714 void parallel_for(ThreadPool & pool, Iterator begin, Iterator end, F && f,
1715 size_t chunk_size = 0)
1716 {
1718 options.pool = &pool;
1719 options.chunk_size = chunk_size;
1720 parallel_for(begin, end, std::forward<F>(f), options);
1721 }
1722
1724 template <typename Iterator, typename F>
1725 void parallel_for(Iterator begin, Iterator end, F && f,
1726 const ParallelOptions & options = {})
1727 {
1728 ThreadPool & pool = parallel_detail::select_pool(options);
1729 const size_t total = std::distance(begin, end);
1730 if (total == 0)
1731 return;
1732
1733 const size_t chunk_size =
1734 parallel_detail::resolve_chunk_size(total, pool.num_threads(), options);
1735
1737 {
1739 if constexpr (std::is_invocable_v<F, Iterator, Iterator>)
1740 {
1741 f(begin, end);
1742 }
1743 else
1744 {
1745 for (Iterator it = begin; it != end; ++it)
1746 {
1748 f(*it);
1749 }
1750 }
1752 return;
1753 }
1754
1755 std::vector<std::future<void>> futures;
1756 futures.reserve((total + chunk_size - 1) / chunk_size);
1757
1758 // Check if F accepts (Iterator, Iterator) or (T&)
1759 if constexpr (std::is_invocable_v<F, Iterator, Iterator>)
1760 {
1761 // Chunk-based function
1762 for (Iterator chunk_begin = begin; chunk_begin < end;)
1763 {
1764 Iterator chunk_end = chunk_begin;
1765 std::advance(chunk_end, std::min(chunk_size,
1766 static_cast<size_t>(std::distance(chunk_begin, end))));
1767
1768 futures.push_back(pool.enqueue([f, chunk_begin, chunk_end, token = options.cancel_token]()
1769 {
1770 parallel_detail::throw_if_canceled(token);
1771 f(chunk_begin, chunk_end);
1772 }));
1773
1774 chunk_begin = chunk_end;
1775 }
1776 }
1777 else
1778 {
1779 // Per-element function
1780 for (Iterator chunk_begin = begin; chunk_begin < end;)
1781 {
1782 Iterator chunk_end = chunk_begin;
1783 std::advance(chunk_end, std::min(chunk_size,
1784 static_cast<size_t>(std::distance(chunk_begin, end))));
1785
1786 futures.push_back(pool.enqueue([f, chunk_begin, chunk_end, token = options.cancel_token]()
1787 {
1788 for (Iterator it = chunk_begin; it != chunk_end; ++it)
1789 {
1790 parallel_detail::throw_if_canceled(token);
1791 f(*it);
1792 }
1793 }));
1794
1795 chunk_begin = chunk_end;
1796 }
1797 }
1798
1799 // Wait for all chunks to complete
1800 for (auto & fut: futures)
1801 fut.get();
1802
1804 }
1805
1835 template <typename InputIt, typename OutputIt, typename F>
1836 OutputIt parallel_transform(ThreadPool & pool, InputIt first, InputIt last,
1837 OutputIt d_first, F && f, size_t chunk_size = 0)
1838 {
1840 options.pool = &pool;
1841 options.chunk_size = chunk_size;
1842 return parallel_transform(first, last, d_first, std::forward<F>(f), options);
1843 }
1844
1846 template <typename InputIt, typename OutputIt, typename F>
1847 OutputIt parallel_transform(InputIt first, InputIt last, OutputIt d_first,
1848 F && f, const ParallelOptions & options = {})
1849 {
1850 ThreadPool & pool = parallel_detail::select_pool(options);
1851 const size_t total = std::distance(first, last);
1852 if (total == 0)
1853 return d_first;
1854
1855 const size_t chunk_size =
1856 parallel_detail::resolve_chunk_size(total, pool.num_threads(), options);
1857
1858 if (parallel_detail::use_sequential_path(total, pool, options))
1859 {
1860 auto in = first;
1861 auto out = d_first;
1862 while (in != last)
1863 {
1864 parallel_detail::throw_if_canceled(options.cancel_token);
1865 *out = f(*in);
1866 ++in;
1867 ++out;
1868 }
1869 parallel_detail::throw_if_canceled(options.cancel_token);
1870 return d_first + total;
1871 }
1872
1873 std::vector<std::future<void>> futures;
1874 futures.reserve((total + chunk_size - 1) / chunk_size);
1875
1876 InputIt chunk_in = first;
1877 OutputIt chunk_out = d_first;
1878
1879 while (chunk_in < last)
1880 {
1881 size_t chunk_len = std::min(chunk_size,
1882 static_cast<size_t>(std::distance(chunk_in, last)));
1883 InputIt chunk_in_end = chunk_in;
1884 std::advance(chunk_in_end, chunk_len);
1885
1886 futures.push_back(pool.enqueue([f, chunk_in, chunk_in_end, chunk_out,
1887 token = options.cancel_token]()
1888 {
1889 InputIt in = chunk_in;
1890 OutputIt out = chunk_out;
1891 while (in != chunk_in_end)
1892 {
1893 parallel_detail::throw_if_canceled(token);
1894 *out = f(*in);
1895 ++in;
1896 ++out;
1897 }
1898 }));
1899
1900 chunk_in = chunk_in_end;
1901 std::advance(chunk_out, chunk_len);
1902 }
1903
1904 for (auto & fut: futures)
1905 fut.get();
1906
1907 parallel_detail::throw_if_canceled(options.cancel_token);
1908
1909 return d_first + total;
1910 }
1911
1946 template <typename Iterator, typename T, typename BinaryOp>
1947 T parallel_reduce(ThreadPool & pool, Iterator first, Iterator last,
1948 T init, BinaryOp op, size_t chunk_size = 0)
1949 {
1951 options.pool = &pool;
1952 options.chunk_size = chunk_size;
1953 return parallel_reduce(first, last, init, op, options);
1954 }
1955
1957 template <typename Iterator, typename T, typename BinaryOp>
1958 T parallel_reduce(Iterator first, Iterator last, T init, BinaryOp op,
1959 const ParallelOptions & options = {})
1960 {
1961 ThreadPool & pool = parallel_detail::select_pool(options);
1962 const size_t total = std::distance(first, last);
1963 if (total == 0)
1964 return init;
1965
1966 const size_t chunk_size =
1967 parallel_detail::resolve_chunk_size(total, pool.num_threads(), options);
1968
1969 if (parallel_detail::use_sequential_path(total, pool, options))
1970 {
1971 T result = init;
1972 for (Iterator it = first; it != last; ++it)
1973 {
1974 parallel_detail::throw_if_canceled(options.cancel_token);
1975 result = op(result, *it);
1976 }
1977 parallel_detail::throw_if_canceled(options.cancel_token);
1978 return result;
1979 }
1980
1981 std::vector<std::future<T>> futures;
1982 futures.reserve((total + chunk_size - 1) / chunk_size);
1983
1984 for (Iterator chunk_begin = first; chunk_begin < last;)
1985 {
1986 Iterator chunk_end = chunk_begin;
1987 std::advance(chunk_end, std::min(chunk_size,
1988 static_cast<size_t>(std::distance(chunk_begin, last))));
1989
1990 futures.push_back(pool.enqueue([op, chunk_begin, chunk_end,
1991 token = options.cancel_token]()
1992 {
1993 parallel_detail::throw_if_canceled(token);
1994 T local_result = *chunk_begin;
1995 for (Iterator it = chunk_begin + 1; it != chunk_end; ++it)
1996 {
1997 parallel_detail::throw_if_canceled(token);
1998 local_result = op(local_result, *it);
1999 }
2000 return local_result;
2001 }));
2002
2003 chunk_begin = chunk_end;
2004 }
2005
2006 // Reduce partial results
2007 T result = init;
2008 for (auto & fut: futures)
2009 result = op(result, fut.get());
2010
2011 parallel_detail::throw_if_canceled(options.cancel_token);
2012
2013 return result;
2014 }
2015
2035 template <typename F>
2036 void parallel_for_index(ThreadPool & pool, size_t start, size_t end, F && f,
2037 size_t chunk_size = 0)
2038 {
2040 options.pool = &pool;
2041 options.chunk_size = chunk_size;
2042 parallel_for_index(start, end, std::forward<F>(f), options);
2043 }
2044
2046 template <typename F>
2047 void parallel_for_index(size_t start, size_t end, F && f,
2048 const ParallelOptions & options = {})
2049 {
2050 ThreadPool & pool = parallel_detail::select_pool(options);
2051 if (start >= end)
2052 return;
2053
2054 const size_t total = end - start;
2055
2056 const size_t chunk_size =
2057 parallel_detail::resolve_chunk_size(total, pool.num_threads(), options);
2058
2059 if (parallel_detail::use_sequential_path(total, pool, options))
2060 {
2061 for (size_t i = start; i < end; ++i)
2062 {
2063 parallel_detail::throw_if_canceled(options.cancel_token);
2064 f(i);
2065 }
2066 parallel_detail::throw_if_canceled(options.cancel_token);
2067 return;
2068 }
2069
2070 std::vector<std::future<void>> futures;
2071 futures.reserve((total + chunk_size - 1) / chunk_size);
2072
2073 for (size_t chunk_start = start; chunk_start < end;)
2074 {
2075 size_t chunk_end = std::min(chunk_start + chunk_size, end);
2076
2077 futures.push_back(pool.enqueue([f, chunk_start, chunk_end,
2078 token = options.cancel_token]()
2079 {
2080 for (size_t i = chunk_start; i < chunk_end; ++i)
2081 {
2082 parallel_detail::throw_if_canceled(token);
2083 f(i);
2084 }
2085 }));
2086
2087 chunk_start = chunk_end;
2088 }
2089
2090 for (auto & fut: futures)
2091 fut.get();
2092
2093 parallel_detail::throw_if_canceled(options.cancel_token);
2094 }
2095
2102 template <typename... Fs>
2103 void parallel_invoke(ThreadPool & pool, Fs &&... fs)
2104 {
2106 options.pool = &pool;
2107 parallel_invoke(options, std::forward<Fs>(fs)...);
2108 }
2109
2111 template <typename... Fs>
2112 void parallel_invoke(const ParallelOptions & options, Fs &&... fs)
2113 {
2114 constexpr size_t task_count = sizeof...(Fs);
2115 if constexpr (task_count == 0)
2116 {
2117 return;
2118 }
2119 else
2120 {
2121 ThreadPool & pool = parallel_detail::select_pool(options);
2122
2123 if (parallel_detail::use_sequential_path(task_count, pool, options))
2124 {
2125 auto invoke_one = [&](auto && fn)
2126 {
2127 parallel_detail::throw_if_canceled(options.cancel_token);
2128 if constexpr (std::is_void_v<std::invoke_result_t<decltype(fn)>>)
2129 std::invoke(std::forward<decltype(fn)>(fn));
2130 else
2131 static_cast<void>(std::invoke(std::forward<decltype(fn)>(fn)));
2132 };
2133
2134 (invoke_one(std::forward<Fs>(fs)), ...);
2135 parallel_detail::throw_if_canceled(options.cancel_token);
2136 return;
2137 }
2138
2139 std::vector<std::future<void>> futures;
2140 futures.reserve(task_count);
2141
2142 auto launch_one = [&](auto && fn)
2143 {
2144 futures.push_back(pool.enqueue(
2145 [func = std::forward<decltype(fn)>(fn),
2146 token = options.cancel_token]() mutable
2147 {
2148 parallel_detail::throw_if_canceled(token);
2149 if constexpr (std::is_void_v<std::invoke_result_t<decltype(func) &>>)
2150 std::invoke(func);
2151 else
2152 static_cast<void>(std::invoke(func));
2153 }));
2154 };
2155
2156 (launch_one(std::forward<Fs>(fs)), ...);
2157
2158 std::exception_ptr first_exception;
2159 for (auto & fut: futures)
2160 {
2161 try
2162 {
2163 fut.get();
2164 }
2165 catch (...)
2166 {
2167 if (first_exception == nullptr)
2168 first_exception = std::current_exception();
2169 }
2170 }
2171
2172 if (first_exception != nullptr)
2173 std::rethrow_exception(first_exception);
2174
2175 parallel_detail::throw_if_canceled(options.cancel_token);
2176 }
2177 }
2178
2185 template <typename InputIt, typename OutputIt, typename BinaryOp>
2186 OutputIt pscan(ThreadPool & pool, InputIt first, InputIt last,
2187 OutputIt d_first, BinaryOp op, size_t chunk_size = 0)
2188 {
2190 options.pool = &pool;
2191 options.chunk_size = chunk_size;
2192 return pscan(first, last, d_first, op, options);
2193 }
2194
2196 template <typename InputIt, typename OutputIt, typename BinaryOp>
2197 OutputIt pscan(InputIt first, InputIt last, OutputIt d_first,
2198 BinaryOp op, const ParallelOptions & options = {})
2199 {
2200 using Value = std::decay_t<std::invoke_result_t<BinaryOp, decltype(*first), decltype(*first)>>;
2201
2202 ThreadPool & pool = parallel_detail::select_pool(options);
2203 const size_t total = std::distance(first, last);
2204 if (total == 0)
2205 return d_first;
2206
2207 const size_t chunk_size =
2208 parallel_detail::resolve_chunk_size(total, pool.num_threads(), options);
2209
2210 if (parallel_detail::use_sequential_path(total, pool, options))
2211 {
2212 parallel_detail::throw_if_canceled(options.cancel_token);
2213
2214 InputIt in = first;
2215 OutputIt out = d_first;
2216 Value running = *in;
2217 *out = running;
2218 ++in;
2219 ++out;
2220
2221 while (in != last)
2222 {
2223 parallel_detail::throw_if_canceled(options.cancel_token);
2224 running = op(running, *in);
2225 *out = running;
2226 ++in;
2227 ++out;
2228 }
2229
2230 parallel_detail::throw_if_canceled(options.cancel_token);
2231 return d_first + total;
2232 }
2233
2234 const size_t num_chunks = (total + chunk_size - 1) / chunk_size;
2235 std::vector<std::optional<Value>> partials(total);
2236 std::vector<std::optional<Value>> chunk_totals(num_chunks);
2237 std::vector<std::future<void>> futures;
2238 futures.reserve(num_chunks);
2239
2240 for (size_t chunk_idx = 0; chunk_idx < num_chunks; ++chunk_idx)
2241 {
2242 const size_t offset = chunk_idx * chunk_size;
2243 const size_t chunk_end = std::min(offset + chunk_size, total);
2244 InputIt chunk_first = first + offset;
2245 InputIt chunk_last = first + chunk_end;
2246 futures.push_back(pool.enqueue(
2247 [chunk_first, chunk_last, &partials, offset,
2248 &chunk_totals, chunk_idx, op,
2249 token = options.cancel_token]() mutable
2250 {
2251 parallel_detail::throw_if_canceled(token);
2252
2253 InputIt in = chunk_first;
2254 Value running = *in;
2255 partials[offset].emplace(running);
2256 ++in;
2257 size_t out_idx = offset + 1;
2258
2259 while (in != chunk_last)
2260 {
2261 parallel_detail::throw_if_canceled(token);
2262 running = op(running, *in);
2263 partials[out_idx++].emplace(running);
2264 ++in;
2265 }
2266
2267 chunk_totals[chunk_idx].emplace(running);
2268 }));
2269 }
2270
2271 for (auto & fut: futures)
2272 fut.get();
2273
2274 parallel_detail::throw_if_canceled(options.cancel_token);
2275
2276 if (num_chunks > 1)
2277 {
2278 std::vector<std::optional<Value>> carries(num_chunks);
2279 for (size_t i = 1; i < num_chunks; ++i)
2280 {
2281 parallel_detail::throw_if_canceled(options.cancel_token);
2282 carries[i].emplace((i == 1)
2283 ? *chunk_totals[0]
2284 : op(*carries[i - 1], *chunk_totals[i - 1]));
2285 }
2286
2287 std::vector<std::future<void>> adjust_futures;
2288 adjust_futures.reserve(num_chunks - 1);
2289
2290 for (size_t chunk_idx = 1; chunk_idx < num_chunks; ++chunk_idx)
2291 {
2292 const size_t offset = chunk_idx * chunk_size;
2293 const size_t chunk_end = std::min(offset + chunk_size, total);
2294 Value carry = *carries[chunk_idx];
2295
2296 adjust_futures.push_back(pool.enqueue(
2297 [&partials, chunk_end, offset, carry, op,
2298 token = options.cancel_token]() mutable
2299 {
2300 for (size_t i = offset; i < chunk_end; ++i)
2301 {
2302 parallel_detail::throw_if_canceled(token);
2303 partials[i] = op(carry, *partials[i]);
2304 }
2305 }));
2306 }
2307
2308 for (auto & fut: adjust_futures)
2309 fut.get();
2310 }
2311
2312 OutputIt out = d_first;
2313 for (auto & partial: partials)
2314 {
2315 *out = std::move(*partial);
2316 ++out;
2317 }
2318
2319 parallel_detail::throw_if_canceled(options.cancel_token);
2320 return d_first + total;
2321 }
2322
2328 template <typename InputIt, typename OutputIt, typename T, typename BinaryOp>
2329 OutputIt pexclusive_scan(ThreadPool & pool, InputIt first, InputIt last,
2330 OutputIt d_first, T init, BinaryOp op,
2331 size_t chunk_size = 0)
2332 {
2334 options.pool = &pool;
2335 options.chunk_size = chunk_size;
2336 return pexclusive_scan(first, last, d_first, init, op, options);
2337 }
2338
2340 template <typename InputIt, typename OutputIt, typename T, typename BinaryOp>
2341 OutputIt pexclusive_scan(InputIt first, InputIt last, OutputIt d_first,
2342 T init, BinaryOp op, const ParallelOptions & options = {})
2343 {
2344 using Value = std::decay_t<T>;
2345
2346 ThreadPool & pool = parallel_detail::select_pool(options);
2347 const size_t total = std::distance(first, last);
2348 if (total == 0)
2349 return d_first;
2350
2351 if (parallel_detail::use_sequential_path(total, pool, options))
2352 {
2353 T running = init;
2354 for (size_t i = 0; i < total; ++i)
2355 {
2356 parallel_detail::throw_if_canceled(options.cancel_token);
2357 d_first[i] = running;
2358 running = op(running, first[i]);
2359 }
2360 parallel_detail::throw_if_canceled(options.cancel_token);
2361 return d_first + total;
2362 }
2363
2364 std::vector<std::optional<Value>> inclusive(total);
2365 pscan(first, last, inclusive.begin(), op, options);
2366
2367 parallel_for_index(0, total,
2368 [&](size_t i)
2369 {
2370 if (i == 0)
2371 d_first[i] = init;
2372 else
2373 d_first[i] = op(init, *inclusive[i - 1]);
2374 },
2375 options);
2376
2377 parallel_detail::throw_if_canceled(options.cancel_token);
2378 return d_first + total;
2379 }
2380
2387 template <typename InputIt1, typename InputIt2, typename OutputIt,
2388 typename Compare = std::less<>>
2389 OutputIt pmerge(ThreadPool & pool,
2390 InputIt1 first1, InputIt1 last1,
2391 InputIt2 first2, InputIt2 last2,
2392 OutputIt d_first, Compare comp = Compare{},
2393 size_t chunk_size = 0)
2394 {
2395 ParallelOptions options;
2396 options.pool = &pool;
2397 options.chunk_size = chunk_size;
2398 return pmerge(first1, last1, first2, last2, d_first, std::move(comp), options);
2399 }
2400
2402 template <typename InputIt1, typename InputIt2, typename OutputIt,
2403 typename Compare = std::less<>>
2404 OutputIt pmerge(InputIt1 first1, InputIt1 last1,
2405 InputIt2 first2, InputIt2 last2,
2406 OutputIt d_first, Compare comp = Compare{},
2407 const ParallelOptions & options = {})
2408 {
2409 ThreadPool & pool = parallel_detail::select_pool(options);
2410 const size_t n1 = std::distance(first1, last1);
2411 const size_t n2 = std::distance(first2, last2);
2412 const size_t total = n1 + n2;
2413
2414 if (total == 0)
2415 return d_first;
2416
2417 if (parallel_detail::use_sequential_path(total, pool, options) or n1 == 0 or n2 == 0)
2418 {
2419 parallel_detail::merge_sequential(first1, last1, first2, last2, d_first,
2420 comp, options.cancel_token);
2421 parallel_detail::throw_if_canceled(options.cancel_token);
2422 return d_first + total;
2423 }
2424
2425 const size_t chunk_hint =
2426 parallel_detail::resolve_chunk_size(total, pool.num_threads(), options);
2427 const size_t desired_tasks = std::max<size_t>(1, (total + chunk_hint - 1) / chunk_hint);
2428
2429 std::vector<std::future<void>> futures;
2430
2431 if (n1 >= n2)
2432 {
2433 const size_t task_count = std::max<size_t>(1, std::min(desired_tasks, n1));
2434 const size_t base_chunk = (n1 + task_count - 1) / task_count;
2435 futures.reserve(task_count);
2436
2437 size_t left_offset = 0;
2438 size_t right_offset = 0;
2439 for (size_t task = 0; task < task_count; ++task)
2440 {
2441 parallel_detail::throw_if_canceled(options.cancel_token);
2442 const size_t next_left = std::min(left_offset + base_chunk, n1);
2443 const size_t next_right =
2444 (next_left < n1)
2445 ? static_cast<size_t>(
2446 std::lower_bound(first2 + right_offset, last2,
2447 first1[next_left], comp) - first2)
2448 : n2;
2449
2450 futures.push_back(pool.enqueue(
2451 [left_begin = first1 + left_offset,
2452 left_end = first1 + next_left,
2453 right_begin = first2 + right_offset,
2454 right_end = first2 + next_right,
2455 out = d_first + left_offset + right_offset,
2456 comp, token = options.cancel_token]() mutable
2457 {
2458 parallel_detail::merge_sequential(left_begin, left_end,
2459 right_begin, right_end,
2460 out, comp, token);
2461 }));
2462
2463 left_offset = next_left;
2464 right_offset = next_right;
2465 }
2466 }
2467 else
2468 {
2469 const size_t task_count = std::max<size_t>(1, std::min(desired_tasks, n2));
2470 const size_t base_chunk = (n2 + task_count - 1) / task_count;
2471 futures.reserve(task_count);
2472
2473 size_t left_offset = 0;
2474 size_t right_offset = 0;
2475 for (size_t task = 0; task < task_count; ++task)
2476 {
2477 parallel_detail::throw_if_canceled(options.cancel_token);
2478 const size_t next_right = std::min(right_offset + base_chunk, n2);
2479 const size_t next_left =
2480 (next_right < n2)
2481 ? static_cast<size_t>(
2482 std::upper_bound(first1 + left_offset, last1,
2483 first2[next_right], comp) - first1)
2484 : n1;
2485
2486 futures.push_back(pool.enqueue(
2487 [left_begin = first1 + left_offset,
2488 left_end = first1 + next_left,
2489 right_begin = first2 + right_offset,
2490 right_end = first2 + next_right,
2491 out = d_first + left_offset + right_offset,
2492 comp, token = options.cancel_token]() mutable
2493 {
2494 parallel_detail::merge_sequential(left_begin, left_end,
2495 right_begin, right_end,
2496 out, comp, token);
2497 }));
2498
2499 left_offset = next_left;
2500 right_offset = next_right;
2501 }
2502 }
2503
2504 for (auto & fut: futures)
2505 fut.get();
2506
2507 parallel_detail::throw_if_canceled(options.cancel_token);
2508 return d_first + total;
2509 }
2510
2525 {
2526 static ThreadPool pool;
2527 return pool;
2528 }
2529
2537 {
2538 ThreadPool *pool_ = nullptr;
2539 std::vector<std::future<void>> tasks_;
2540
2541 template <typename F, typename... Args>
2542 static auto make_invocable(F && f, Args &&... args)
2543 {
2544 return [func = std::forward<F>(f),
2545 args_tuple = std::make_tuple(std::forward<Args>(args)...)]() mutable
2546 {
2547 return std::apply([&func](auto &&... a)
2548 {
2549 return std::invoke(std::move(func), std::forward<decltype(a)>(a)...);
2550 }, std::move(args_tuple));
2551 };
2552 }
2553
2554 void drain(const bool propagate)
2555 {
2556 std::exception_ptr first_exception;
2557 for (auto & task: tasks_)
2558 {
2559 try
2560 {
2561 task.get();
2562 }
2563 catch (...)
2564 {
2565 if (first_exception == nullptr)
2566 first_exception = std::current_exception();
2567 }
2568 }
2569 tasks_.clear();
2570 if (propagate and first_exception != nullptr)
2571 std::rethrow_exception(first_exception);
2572 }
2573
2574 public:
2575 explicit TaskGroup(ThreadPool & pool = default_pool()) noexcept
2576 : pool_(&pool) {}
2577
2579 TaskGroup(const TaskGroup &) = delete;
2580
2582 TaskGroup &operator=(const TaskGroup &) = delete;
2583
2585 TaskGroup(TaskGroup &&) = delete;
2586
2589
2590 ~TaskGroup() { drain(false); }
2591
2593 template <typename F, typename... Args>
2594 void launch(F && f, Args &&... args)
2595 {
2596 auto invocable = make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
2597 tasks_.push_back(pool_->enqueue([invocable = std::move(invocable)]() mutable
2598 {
2599 if constexpr (std::is_void_v<std::invoke_result_t<decltype(invocable) &>>)
2600 invocable();
2601 else
2602 static_cast<void>(invocable());
2603 }));
2604 }
2605
2607 template <typename F, typename... Args>
2608 void run(F && f, Args &&... args)
2609 {
2610 launch(std::forward<F>(f), std::forward<Args>(args)...);
2611 }
2612
2614 void wait() { drain(true); }
2615
2617 [[nodiscard]] size_t size() const noexcept { return tasks_.size(); }
2618
2620 [[nodiscard]] bool is_empty() const noexcept { return tasks_.empty(); }
2621 };
2622} // end namespace Aleph
2623
2624#endif // ALEPH_THREAD_POOL_H
size_t size_t int32_t * out
Definition ca-c-api.h:120
Cooperative cancellation source paired with CancellationToken.
CancellationToken token() const noexcept
Return a token observing this source.
bool stop_requested() const noexcept
Return true if cancellation has already been requested.
std::shared_ptr< cancellation_detail::Exact_State > state_
void request_cancel() noexcept
Request cancellation for all derived tokens.
CancellationSource()=default
Default constructor.
void reset()
Reset the source so future tokens observe a fresh state.
void cancel() noexcept
Synonym for request_cancel().
RAII guard for condition variable cancellation registration.
std::shared_ptr< cancellation_detail::Exact_State > locked_state_
std::shared_ptr< CancellationState > state_
ConditionVariableRegistration(std::shared_ptr< CancellationState > state, std::condition_variable *cv) noexcept
Construct with shared state and condition variable.
ConditionVariableRegistration()=default
Default constructor.
std::list< cancellation_detail::Locked_Observer >::iterator locked_
ConditionVariableRegistration(ConditionVariableRegistration &&other) noexcept
ConditionVariableRegistration(std::shared_ptr< cancellation_detail::Exact_State > state, const std::list< cancellation_detail::Locked_Observer >::iterator it) noexcept
ConditionVariableRegistration(const ConditionVariableRegistration &)=delete
Deleted copy constructor.
Read-only cooperative cancellation token.
ConditionVariableRegistration notify_on_cancel(std::condition_variable &cv) const
Request notification of a condition variable on cancellation.
bool stop_requested() const noexcept
Return true if cancellation has been requested.
CancellationToken()=default
Default constructor.
std::shared_ptr< cancellation_detail::Exact_State > state_
bool valid() const noexcept
Return true if the token is connected to a source.
bool is_cancellation_requested() const noexcept
Synonym for stop_requested().
ConditionVariableRegistration notify_on_cancel(std::condition_variable &cv, std::mutex &mutex) const
Request notification of a condition variable on cancellation, without missing it.
void throw_if_cancellation_requested() const
Throw operation_canceled if cancellation was requested.
CancellationToken(std::shared_ptr< cancellation_detail::Exact_State > state) noexcept
Minimal structured-concurrency helper over ThreadPool futures.
bool is_empty() const noexcept
Return true if the group has no pending tasks.
TaskGroup & operator=(const TaskGroup &)=delete
Deleted copy assignment operator.
void run(F &&f, Args &&... args)
Compatibility wrapper for launch().
std::vector< std::future< void > > tasks_
TaskGroup(ThreadPool &pool=default_pool()) noexcept
void wait()
Wait for all launched tasks and rethrow the first exception.
size_t size() const noexcept
Return the number of tasks currently tracked by the group.
TaskGroup(TaskGroup &&)=delete
Deleted move constructor.
void drain(const bool propagate)
TaskGroup & operator=(TaskGroup &&)=delete
Deleted move assignment operator.
static auto make_invocable(F &&f, Args &&... args)
TaskGroup(const TaskGroup &)=delete
Deleted copy constructor.
void launch(F &&f, Args &&... args)
Launch a task that belongs to this group.
A reusable thread pool for efficient parallel task execution.
bool try_enqueue_detached(F &&f, Args &&... args)
Try to submit a detached task without blocking or throwing.
size_t num_threads() const noexcept
Get the number of worker threads.
std::mutex queue_mutex
bool wait_all_for(std::chrono::duration< Rep, Period > timeout)
Wait until all current tasks complete, with timeout.
void enqueue_detached(F &&f, Args &&... args)
Submit a task without tracking the result (fire-and-forget).
void set_exception_callback(ExceptionCallback callback)
Set callback for exceptions in detached tasks.
auto enqueue_batch(F &&f, const Container &args_list) -> std::vector< std::future< decltype(std::apply(f, *std::begin(args_list)))> >
Submit multiple tasks with a single notification.
size_t running_tasks() const noexcept
Get the number of tasks currently being executed.
bool is_idle() const
Check if the pool is idle (no pending or running tasks).
auto enqueue_bounded(F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > >
Submit a task with backpressure and memory protection.
ThreadPool(ThreadPool &&)=delete
Deleted move constructor.
static auto make_invocable(F &&f, Args &&... args)
Helper to create a callable from function + arguments using std::invoke.
std::condition_variable idle_condition
Notifies wait_all() of idle state.
auto enqueue_bulk(F &&f, const Container &args_container) -> std::vector< std::future< std::invoke_result_t< F, typename Container::value_type > > >
Submit multiple tasks and collect all futures.
void resize(size_t new_size)
Resize the pool to a different number of workers.
ThreadPoolStats get_stats() const
Get current pool statistics.
void reset_stats()
Reset statistics counters to zero.
bool wait_all_until(std::chrono::time_point< Clock, Duration > deadline)
Wait until all current tasks complete, with deadline.
std::condition_variable space_available
Notifies enqueuers of queue space.
void start_workers(size_t n)
Start n worker threads.
std::atomic< size_t > peak_queue_size_
ThreadPool & operator=(ThreadPool &&)=delete
Deleted move assignment operator.
bool is_stopped() const noexcept
Check if the pool has been shut down.
void wait_all(const std::chrono::milliseconds poll_interval=std::chrono::milliseconds(1))
Wait until all current tasks complete.
std::pair< size_t, size_t > get_queue_limits() const
Get current queue limits.
ThreadPool(size_t n_threads=std::thread::hardware_concurrency())
Construct a thread pool with specified number of workers.
std::atomic< size_t > tasks_failed_
size_t hard_limit_
Exception threshold.
~ThreadPool()
Destructor - stops all workers and waits for completion.
size_t soft_limit_
Block threshold.
std::condition_variable condition
Notifies workers of new tasks.
std::vector< std::thread > workers
auto enqueue(F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > >
Submit a task for execution and get a future for the result.
void enqueue_bounded_detached(F &&f, Args &&... args)
Submit a task with backpressure, without tracking result.
void stop_workers()
Stop and join all workers.
std::atomic< bool > stop
void worker_loop()
Worker thread main loop.
std::atomic< size_t > active_tasks
size_t pending_tasks() const
Get the number of pending tasks in the queue.
void set_queue_limits(const size_t soft_limit, const size_t hard_limit=std::numeric_limits< size_t >::max())
Set queue limits for bounded enqueue operations.
void shutdown()
Shut down the pool, completing all pending tasks.
std::atomic< size_t > tasks_completed_
ThreadPool(const ThreadPool &)=delete
Deleted copy constructor.
auto try_enqueue(F &&f, Args &&... args) -> std::optional< std::future< std::invoke_result_t< F, Args... > > >
Try to submit a task without blocking or throwing.
ThreadPool & operator=(const ThreadPool &)=delete
Deleted copy assignment operator.
std::queue< std::unique_ptr< TaskBase > > tasks
ExceptionCallback exception_callback_
Exception thrown when cooperative cancellation is observed.
operation_canceled(const std::string &message)
Exception thrown when the task queue exceeds its hard limit.
size_t current_size() const noexcept
Current queue size when exception was thrown.
queue_overflow_error(size_t current_size, size_t hard_limit)
size_t hard_limit() const noexcept
Hard limit that was exceeded.
const long double offset[]
Offset values indexed by symbol string length (bounded by MAX_OFFSET_INDEX)
FFT< double > F
ThreadPool & select_pool(const ParallelOptions &options)
size_t resolve_chunk_size(const size_t total, const size_t num_threads, const ParallelOptions &options, const size_t min_chunk=1)
void throw_if_canceled(const CancellationToken &token)
void merge_sequential(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp, const CancellationToken &token)
size_t chunk_size(const size_t n, const size_t num_threads, const size_t min_chunk=64)
Calculate optimal chunk size based on data size and thread count.
bool use_sequential_path(const size_t total, const ThreadPool &pool, const ParallelOptions &options) noexcept
Main namespace for Aleph-w library functions.
T parallel_reduce(ThreadPool &pool, Iterator first, Iterator last, T init, BinaryOp op, size_t chunk_size=0)
Reduce elements in parallel.
OutputIt parallel_transform(ThreadPool &pool, InputIt first, InputIt last, OutputIt d_first, F &&f, size_t chunk_size=0)
Transform elements in parallel and store results.
ThreadPool & default_pool()
Return the default shared thread pool instance.
@ Value
Regular runtime payload stored as Interpreter_Value.
void message(const char *file, int line, const char *format,...)
Print an informational message with file and line info.
Definition ahDefs.C:95
auto pexclusive_scan(ThreadPool &pool, const Container &c, T init, BinaryOp op, size_t chunk_size=0)
Parallel exclusive scan over a container.
void parallel_for_index(ThreadPool &pool, size_t start, size_t end, F &&f, size_t chunk_size=0)
Apply a function to each element in parallel (index-based).
void parallel_for(ThreadPool &pool, Iterator begin, Iterator end, F &&f, size_t chunk_size=0)
Execute a function in parallel over a range.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
auto pmerge(ThreadPool &pool, const Container1 &c1, const Container2 &c2, Compare comp=Compare{}, size_t chunk_size=0)
Parallel merge of two sorted containers.
and
Check uniqueness with explicit hash + equality functors.
auto pscan(ThreadPool &pool, const Container &c, BinaryOp op, size_t chunk_size=0)
Parallel inclusive scan over a container.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
void parallel_invoke(ThreadPool &pool, Fs &&... fs)
Invoke a small set of related callables in parallel.
std::function< void(std::exception_ptr)> ExceptionCallback
Type for exception callback in detached tasks.
STL namespace.
static struct argp_option options[]
Definition ntreepic.C:1890
Shared state for cooperative cancellation.
void register_condition_variable(std::condition_variable *cv)
void notify_observers() noexcept
std::atomic< bool > stop_requested
std::vector< std::condition_variable * > observers
void unregister_condition_variable(std::condition_variable *cv)
Common configuration object for parallel algorithms.
size_t chunk_size
Elements per chunk (0 = auto).
ThreadPool * pool
Executor to use (nullptr = default_pool()).
size_t min_size
Run sequentially below this size.
size_t max_tasks
Maximum number of scheduled tasks (0 = auto).
CancellationToken cancel_token
Cooperative cancellation observer.
Statistics collected by ThreadPool.
double queue_utilization(size_t soft_limit) const noexcept
Queue utilization as percentage (0-100)
size_t current_queue_size
Current pending tasks.
size_t num_workers
Number of worker threads.
size_t tasks_completed
Total tasks completed.
size_t peak_queue_size
Maximum queue size observed.
size_t total_processed() const noexcept
Total tasks processed (completed + failed)
size_t current_active
Currently executing tasks.
size_t tasks_failed
Tasks that threw exceptions (detached)
Type-erased task wrapper.
virtual void execute()=0
virtual ~TaskBase()=default
Virtual destructor.
Concrete task implementation with type preservation.
void execute() override
State created by a CancellationSource.
std::list< Locked_Observer >::iterator register_locked(std::condition_variable &cv, std::mutex &mutex)
Register cv, whose waiters hold mutex.
std::list< Locked_Observer > locked_observers
Registrations made with a mutex, in order, under observer_mutex.
void unregister_locked(const std::list< Locked_Observer >::iterator it) noexcept
End a registration, once no cancellation is notifying it.
void notify_locked_observers() noexcept
Notify every registration made with a mutex.
std::condition_variable not_busy
Notified when an ended registration stops being busy.
A condition variable registered with the mutex of its waiters.
std::condition_variable * cv
Condition variable to notify.
bool removed
Whether its registration has ended.
size_t busy
Cancellations notifying it right now.
std::mutex * mutex
Mutex that its waiters hold.