109#ifndef ALEPH_THREAD_POOL_H
110#define ALEPH_THREAD_POOL_H
116#include <condition_variable>
123#include <type_traits>
145 :
std::runtime_error(
"operation canceled") {}
192 namespace cancellation_detail
200 std::condition_variable *
cv;
232 std::list<Locked_Observer>::iterator
247 not_busy.wait(lock, [&] {
return it->busy == 0; });
268 std::condition_variable *
const cv = it->cv;
269 std::mutex *
const mutex = it->mutex;
272 std::lock_guard<std::mutex> waiter_lock(*mutex);
277 const auto next = std::next(it);
278 if (--it->busy == 0
and it->removed)
294 std::shared_ptr<cancellation_detail::Exact_State>
state_;
297 :
state_(std::move(state)) {}
313 std::shared_ptr<CancellationState>
state_;
314 std::condition_variable *
cv_ =
nullptr;
318 std::list<cancellation_detail::Locked_Observer>::iterator
locked_{};
321 std::shared_ptr<cancellation_detail::Exact_State> state,
322 const std::list<cancellation_detail::Locked_Observer>::iterator it) noexcept
332 state_->unregister_condition_variable(
cv_);
347 std::condition_variable * cv) noexcept
357 :
state_(std::move(other.state_)),
cv_(other.cv_),
370 state_ = std::move(other.state_);
391 return state_ !=
nullptr and state_->stop_requested.load(std::memory_order_relaxed);
408 [[nodiscard]]
bool valid() const noexcept {
return state_ !=
nullptr; }
425 deprecated(
"use notify_on_cancel(cv, mutex), which cannot miss the notification")]]
430 state_->register_condition_variable(&cv);
433 state_->unregister_condition_variable(&cv);
480 std::condition_variable & cv, std::mutex & mutex)
const
497 std::shared_ptr<cancellation_detail::Exact_State>
state_ =
498 std::make_shared<cancellation_detail::Exact_State>();
519 state_->stop_requested.store(
true, std::memory_order_relaxed);
520 state_->notify_observers();
521 state_->notify_locked_observers();
530 return state_->stop_requested.load(std::memory_order_relaxed);
534 void reset() {
state_ = std::make_shared<cancellation_detail::Exact_State>(); }
561 :
std::overflow_error(
"ThreadPool queue overflow: " +
599 if (soft_limit == 0 or soft_limit == std::numeric_limits<size_t>::max())
641 template <
typename F>
652 std::queue<std::unique_ptr<TaskBase>>
tasks;
677 std::unique_ptr<TaskBase> task;
678 bool should_notify_space =
false; {
691 task = std::move(
tasks.front());
697 if (should_notify_space)
721 for (
size_t i = 0; i < n; ++i)
740 if (worker.joinable())
747 template <
typename F,
typename... Args>
751 return [func = std::forward<F>(f),
752 args_tuple = std::make_tuple(std::forward<Args>(args)...)]()
mutable
754 return std::apply([&func](
auto &&... a)
756 return std::invoke(std::move(func), std::forward<
decltype(a)>(a)...);
757 }, std::move(args_tuple));
769 explicit ThreadPool(
size_t n_threads = std::thread::hardware_concurrency())
841 template <
typename F,
typename... Args>
842 [[nodiscard]]
auto enqueue(
F && f, Args &&... args)
843 -> std::future<std::invoke_result_t<
F, Args...>>
845 using return_type = std::invoke_result_t<
F, Args...>;
848 auto invocable =
make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
851 auto promise = std::make_shared<std::promise<return_type>>();
852 std::future<return_type> result = promise->get_future();
858 auto task_func = [invocable = std::move(invocable), promise, completed_counter]()
mutable
862 if constexpr (std::is_void_v<return_type>)
865 promise->set_value();
869 promise->set_value(invocable());
871 ++(*completed_counter);
875 promise->set_exception(std::current_exception());
876 ++(*completed_counter);
882 throw std::runtime_error(
"enqueue on stopped ThreadPool");
884 tasks.push(std::make_unique<
Task<
decltype(task_func)>>(std::move(task_func)));
887 const size_t current_size =
tasks.size();
889 while (current_size > peak
and
923 template <
typename F,
typename... Args>
926 auto invocable =
make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
936 auto task_func = [invocable = std::move(invocable),
937 completed_counter, failed_counter,
938 callback = std::move(callback)]()
mutable
943 ++(*completed_counter);
951 try { callback(std::current_exception()); }
959 throw std::runtime_error(
"enqueue_detached on stopped ThreadPool");
961 tasks.push(std::make_unique<
Task<
decltype(task_func)>>(std::move(task_func)));
964 const size_t current_size =
tasks.size();
966 while (current_size > peak
and
993 template <
typename F,
typename Container>
995 -> std::vector<std::future<std::invoke_result_t<F, typename Container::value_type>>>
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());
1001 for (
const auto & arg: args_container)
1002 results.push_back(
enqueue(f, arg));
1029 const size_t hard_limit = std::numeric_limits<size_t>::max())
1033 hard_limit_ = (hard_limit == std::numeric_limits<size_t>::max()
and
1034 soft_limit != std::numeric_limits<size_t>::max()) ?
1084 template <
typename F,
typename... Args>
1086 -> std::future<std::invoke_result_t<
F, Args...>>
1088 using return_type = std::invoke_result_t<
F, Args...>;
1090 auto invocable =
make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
1092 auto promise = std::make_shared<std::promise<return_type>>();
1093 std::future<return_type> result = promise->get_future();
1095 auto task_func = [invocable = std::move(invocable), promise]()
mutable
1099 if constexpr (std::is_void_v<return_type>)
1102 promise->set_value();
1106 promise->set_value(invocable());
1111 promise->set_exception(std::current_exception());
1127 throw std::runtime_error(
"enqueue_bounded on stopped ThreadPool");
1133 tasks.push(std::make_unique<
Task<
decltype(task_func)>>(std::move(task_func)));
1154 template <
typename F,
typename... Args>
1157 auto invocable =
make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
1159 auto task_func = [invocable = std::move(invocable)]()
mutable
1183 throw std::runtime_error(
"enqueue_bounded_detached on stopped ThreadPool");
1189 tasks.push(std::make_unique<
Task<
decltype(task_func)>>(std::move(task_func)));
1229 template <
typename F,
typename... Args>
1231 -> std::optional<std::future<std::invoke_result_t<
F, Args...>>>
1236 throw std::runtime_error(
"try_enqueue on stopped ThreadPool");
1240 return std::nullopt;
1244 return enqueue(std::forward<F>(f), std::forward<Args>(args)...);
1269 template <
typename F,
typename... Args>
1275 throw std::runtime_error(
"try_enqueue_detached on stopped ThreadPool");
1299 return tasks.size();
1340 if (
stop.exchange(
true))
1346 if (worker.joinable())
1373 if (new_size ==
workers.size())
1377 throw std::runtime_error(
"cannot resize a stopped ThreadPool");
1387 if (worker.joinable())
1404 void wait_all(
const std::chrono::milliseconds poll_interval = std::chrono::milliseconds(1))
1407 std::this_thread::sleep_for(poll_interval);
1419 template <
typename Rep,
typename Period>
1420 [[nodiscard]]
bool wait_all_for(std::chrono::duration<Rep, Period> timeout)
1438 template <
typename Clock,
typename Duration>
1527 template <
typename F,
typename Container>
1529 -> std::vector<std::future<
decltype(std::apply(f, *std::begin(args_list)))>>
1531 using ArgsTuple =
typename Container::value_type;
1532 using return_type =
decltype(std::apply(f, std::declval<ArgsTuple>()));
1534 std::vector<std::future<return_type>> results;
1535 results.reserve(std::distance(std::begin(args_list), std::end(args_list)));
1537 std::vector<std::unique_ptr<TaskBase>> batch_tasks;
1538 batch_tasks.reserve(results.capacity());
1543 for (
const auto & args: args_list)
1545 auto promise = std::make_shared<std::promise<return_type>>();
1546 results.push_back(promise->get_future());
1548 auto task_func = [func = f, args, promise, completed_counter]()
mutable
1552 if constexpr (std::is_void_v<return_type>)
1554 std::apply(func, args);
1555 promise->set_value();
1559 promise->set_value(std::apply(func, args));
1561 ++(*completed_counter);
1565 promise->set_exception(std::current_exception());
1566 ++(*completed_counter);
1570 batch_tasks.push_back(
1571 std::make_unique<
Task<
decltype(task_func)>>(std::move(task_func)));
1576 throw std::runtime_error(
"enqueue_batch on stopped ThreadPool");
1578 for (
auto & task: batch_tasks)
1579 tasks.push(std::move(task));
1582 const size_t current_size =
tasks.size();
1584 while (current_size > peak
and
1599 namespace parallel_detail
1607 const size_t num_threads,
1609 const size_t min_chunk = 1)
1617 total / std::max<size_t>(1, num_threads * 4));
1621 const size_t min_for_cap =
1636 if (
options.cancel_token.stop_requested())
1645 return pool.num_threads() <= 1;
1653 template <
typename InputIt1,
typename InputIt2,
typename OutputIt,
typename Compare>
1655 InputIt2 first2, InputIt2 last2,
1656 OutputIt d_first, Compare comp,
1659 while (first1 != last1
and first2 != last2)
1662 if (comp(*first2, *first1))
1663 *d_first++ = *first2++;
1665 *d_first++ = *first1++;
1668 while (first1 != last1)
1671 *d_first++ = *first1++;
1674 while (first2 != last2)
1677 *d_first++ = *first2++;
1713 template <
typename Iterator,
typename F>
1715 size_t chunk_size = 0)
1719 options.chunk_size = chunk_size;
1724 template <
typename Iterator,
typename F>
1729 const size_t total = std::distance(begin, end);
1733 const size_t chunk_size =
1739 if constexpr (std::is_invocable_v<F, Iterator, Iterator>)
1745 for (Iterator it = begin; it != end; ++it)
1755 std::vector<std::future<void>> futures;
1756 futures.reserve((total + chunk_size - 1) / chunk_size);
1759 if constexpr (std::is_invocable_v<F, Iterator, Iterator>)
1762 for (Iterator chunk_begin = begin; chunk_begin < end;)
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))));
1768 futures.push_back(pool.enqueue([f, chunk_begin, chunk_end, token =
options.cancel_token]()
1770 parallel_detail::throw_if_canceled(token);
1771 f(chunk_begin, chunk_end);
1774 chunk_begin = chunk_end;
1780 for (Iterator chunk_begin = begin; chunk_begin < end;)
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))));
1786 futures.push_back(pool.enqueue([f, chunk_begin, chunk_end, token =
options.cancel_token]()
1788 for (Iterator it = chunk_begin; it != chunk_end; ++it)
1790 parallel_detail::throw_if_canceled(token);
1795 chunk_begin = chunk_end;
1800 for (
auto & fut: futures)
1835 template <
typename InputIt,
typename OutputIt,
typename F>
1837 OutputIt d_first,
F && f,
size_t chunk_size = 0)
1841 options.chunk_size = chunk_size;
1846 template <
typename InputIt,
typename OutputIt,
typename F>
1850 ThreadPool & pool = parallel_detail::select_pool(
options);
1851 const size_t total = std::distance(first, last);
1855 const size_t chunk_size =
1856 parallel_detail::resolve_chunk_size(total, pool.num_threads(),
options);
1858 if (parallel_detail::use_sequential_path(total, pool,
options))
1864 parallel_detail::throw_if_canceled(
options.cancel_token);
1869 parallel_detail::throw_if_canceled(
options.cancel_token);
1870 return d_first + total;
1873 std::vector<std::future<void>> futures;
1874 futures.reserve((total + chunk_size - 1) / chunk_size);
1876 InputIt chunk_in = first;
1877 OutputIt chunk_out = d_first;
1879 while (chunk_in < last)
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);
1886 futures.push_back(pool.enqueue([f, chunk_in, chunk_in_end, chunk_out,
1887 token =
options.cancel_token]()
1889 InputIt in = chunk_in;
1890 OutputIt out = chunk_out;
1891 while (in != chunk_in_end)
1893 parallel_detail::throw_if_canceled(token);
1900 chunk_in = chunk_in_end;
1901 std::advance(chunk_out, chunk_len);
1904 for (
auto & fut: futures)
1907 parallel_detail::throw_if_canceled(
options.cancel_token);
1909 return d_first + total;
1946 template <
typename Iterator,
typename T,
typename BinaryOp>
1948 T init, BinaryOp op,
size_t chunk_size = 0)
1952 options.chunk_size = chunk_size;
1957 template <
typename Iterator,
typename T,
typename BinaryOp>
1961 ThreadPool & pool = parallel_detail::select_pool(
options);
1962 const size_t total = std::distance(first, last);
1966 const size_t chunk_size =
1967 parallel_detail::resolve_chunk_size(total, pool.num_threads(),
options);
1969 if (parallel_detail::use_sequential_path(total, pool,
options))
1972 for (Iterator it = first; it != last; ++it)
1974 parallel_detail::throw_if_canceled(
options.cancel_token);
1975 result = op(result, *it);
1977 parallel_detail::throw_if_canceled(
options.cancel_token);
1981 std::vector<std::future<T>> futures;
1982 futures.reserve((total + chunk_size - 1) / chunk_size);
1984 for (Iterator chunk_begin = first; chunk_begin < last;)
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))));
1990 futures.push_back(pool.enqueue([op, chunk_begin, chunk_end,
1991 token =
options.cancel_token]()
1993 parallel_detail::throw_if_canceled(token);
1994 T local_result = *chunk_begin;
1995 for (Iterator it = chunk_begin + 1; it != chunk_end; ++it)
1997 parallel_detail::throw_if_canceled(token);
1998 local_result = op(local_result, *it);
2000 return local_result;
2003 chunk_begin = chunk_end;
2008 for (
auto & fut: futures)
2009 result = op(result, fut.get());
2011 parallel_detail::throw_if_canceled(
options.cancel_token);
2035 template <
typename F>
2037 size_t chunk_size = 0)
2041 options.chunk_size = chunk_size;
2046 template <
typename F>
2050 ThreadPool & pool = parallel_detail::select_pool(
options);
2054 const size_t total = end - start;
2056 const size_t chunk_size =
2057 parallel_detail::resolve_chunk_size(total, pool.num_threads(),
options);
2059 if (parallel_detail::use_sequential_path(total, pool,
options))
2061 for (
size_t i = start; i < end; ++i)
2063 parallel_detail::throw_if_canceled(
options.cancel_token);
2066 parallel_detail::throw_if_canceled(
options.cancel_token);
2070 std::vector<std::future<void>> futures;
2071 futures.reserve((total + chunk_size - 1) / chunk_size);
2073 for (
size_t chunk_start = start; chunk_start < end;)
2075 size_t chunk_end = std::min(chunk_start + chunk_size, end);
2077 futures.push_back(pool.enqueue([f, chunk_start, chunk_end,
2078 token =
options.cancel_token]()
2080 for (size_t i = chunk_start; i < chunk_end; ++i)
2082 parallel_detail::throw_if_canceled(token);
2087 chunk_start = chunk_end;
2090 for (
auto & fut: futures)
2093 parallel_detail::throw_if_canceled(
options.cancel_token);
2102 template <
typename... Fs>
2111 template <
typename... Fs>
2114 constexpr size_t task_count =
sizeof...(Fs);
2115 if constexpr (task_count == 0)
2123 if (parallel_detail::use_sequential_path(task_count, pool,
options))
2125 auto invoke_one = [&](
auto && fn)
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));
2131 static_cast<void>(std::invoke(std::forward<
decltype(fn)>(fn)));
2134 (invoke_one(std::forward<Fs>(fs)), ...);
2135 parallel_detail::throw_if_canceled(
options.cancel_token);
2139 std::vector<std::future<void>> futures;
2140 futures.reserve(task_count);
2142 auto launch_one = [&](
auto && fn)
2144 futures.push_back(pool.
enqueue(
2145 [func = std::forward<
decltype(fn)>(fn),
2146 token =
options.cancel_token]()
mutable
2148 parallel_detail::throw_if_canceled(token);
2149 if constexpr (std::is_void_v<std::invoke_result_t<decltype(func) &>>)
2152 static_cast<void>(std::invoke(func));
2156 (launch_one(std::forward<Fs>(fs)), ...);
2158 std::exception_ptr first_exception;
2159 for (
auto & fut: futures)
2167 if (first_exception ==
nullptr)
2168 first_exception = std::current_exception();
2172 if (first_exception !=
nullptr)
2173 std::rethrow_exception(first_exception);
2175 parallel_detail::throw_if_canceled(
options.cancel_token);
2185 template <
typename InputIt,
typename OutputIt,
typename BinaryOp>
2187 OutputIt d_first, BinaryOp op,
size_t chunk_size = 0)
2191 options.chunk_size = chunk_size;
2196 template <
typename InputIt,
typename OutputIt,
typename BinaryOp>
2197 OutputIt
pscan(InputIt first, InputIt last, OutputIt d_first,
2200 using Value = std::decay_t<std::invoke_result_t<BinaryOp,
decltype(*first),
decltype(*first)>>;
2202 ThreadPool & pool = parallel_detail::select_pool(
options);
2203 const size_t total = std::distance(first, last);
2207 const size_t chunk_size =
2208 parallel_detail::resolve_chunk_size(total, pool.num_threads(),
options);
2210 if (parallel_detail::use_sequential_path(total, pool,
options))
2212 parallel_detail::throw_if_canceled(
options.cancel_token);
2215 OutputIt
out = d_first;
2216 Value running = *in;
2223 parallel_detail::throw_if_canceled(
options.cancel_token);
2224 running = op(running, *in);
2230 parallel_detail::throw_if_canceled(
options.cancel_token);
2231 return d_first + total;
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);
2240 for (
size_t chunk_idx = 0; chunk_idx < num_chunks; ++chunk_idx)
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
2251 parallel_detail::throw_if_canceled(token);
2253 InputIt in = chunk_first;
2254 Value running = *in;
2255 partials[offset].emplace(running);
2257 size_t out_idx = offset + 1;
2259 while (in != chunk_last)
2261 parallel_detail::throw_if_canceled(token);
2262 running = op(running, *in);
2263 partials[out_idx++].emplace(running);
2267 chunk_totals[chunk_idx].emplace(running);
2271 for (
auto & fut: futures)
2274 parallel_detail::throw_if_canceled(
options.cancel_token);
2278 std::vector<std::optional<Value>> carries(num_chunks);
2279 for (
size_t i = 1; i < num_chunks; ++i)
2281 parallel_detail::throw_if_canceled(
options.cancel_token);
2282 carries[i].emplace((i == 1)
2284 : op(*carries[i - 1], *chunk_totals[i - 1]));
2287 std::vector<std::future<void>> adjust_futures;
2288 adjust_futures.reserve(num_chunks - 1);
2290 for (
size_t chunk_idx = 1; chunk_idx < num_chunks; ++chunk_idx)
2293 const size_t chunk_end = std::min(
offset + chunk_size, total);
2294 Value carry = *carries[chunk_idx];
2296 adjust_futures.push_back(pool.enqueue(
2297 [&partials, chunk_end,
offset, carry, op,
2298 token =
options.cancel_token]()
mutable
2300 for (size_t i = offset; i < chunk_end; ++i)
2302 parallel_detail::throw_if_canceled(token);
2303 partials[i] = op(carry, *partials[i]);
2308 for (
auto & fut: adjust_futures)
2312 OutputIt
out = d_first;
2313 for (
auto & partial: partials)
2315 *
out = std::move(*partial);
2319 parallel_detail::throw_if_canceled(
options.cancel_token);
2320 return d_first + total;
2328 template <
typename InputIt,
typename OutputIt,
typename T,
typename BinaryOp>
2330 OutputIt d_first,
T init, BinaryOp op,
2331 size_t chunk_size = 0)
2335 options.chunk_size = chunk_size;
2340 template <
typename InputIt,
typename OutputIt,
typename T,
typename BinaryOp>
2344 using Value = std::decay_t<T>;
2346 ThreadPool & pool = parallel_detail::select_pool(
options);
2347 const size_t total = std::distance(first, last);
2351 if (parallel_detail::use_sequential_path(total, pool,
options))
2354 for (
size_t i = 0; i < total; ++i)
2356 parallel_detail::throw_if_canceled(
options.cancel_token);
2357 d_first[i] = running;
2358 running = op(running, first[i]);
2360 parallel_detail::throw_if_canceled(
options.cancel_token);
2361 return d_first + total;
2364 std::vector<std::optional<Value>> inclusive(total);
2373 d_first[i] = op(init, *inclusive[i - 1]);
2377 parallel_detail::throw_if_canceled(
options.cancel_token);
2378 return d_first + total;
2387 template <
typename InputIt1,
typename InputIt2,
typename OutputIt,
2388 typename Compare = std::less<>>
2390 InputIt1 first1, InputIt1 last1,
2391 InputIt2 first2, InputIt2 last2,
2392 OutputIt d_first, Compare comp = Compare{},
2393 size_t chunk_size = 0)
2397 options.chunk_size = chunk_size;
2398 return pmerge(first1, last1, first2, last2, d_first, std::move(comp),
options);
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 = {})
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;
2417 if (parallel_detail::use_sequential_path(total, pool,
options) or n1 == 0 or n2 == 0)
2419 parallel_detail::merge_sequential(first1, last1, first2, last2, d_first,
2421 parallel_detail::throw_if_canceled(
options.cancel_token);
2422 return d_first + total;
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);
2429 std::vector<std::future<void>> futures;
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);
2437 size_t left_offset = 0;
2438 size_t right_offset = 0;
2439 for (
size_t task = 0; task < task_count; ++task)
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 =
2445 ?
static_cast<size_t>(
2446 std::lower_bound(first2 + right_offset, last2,
2447 first1[next_left], comp) - first2)
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
2458 parallel_detail::merge_sequential(left_begin, left_end,
2459 right_begin, right_end,
2463 left_offset = next_left;
2464 right_offset = next_right;
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);
2473 size_t left_offset = 0;
2474 size_t right_offset = 0;
2475 for (
size_t task = 0; task < task_count; ++task)
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 =
2481 ?
static_cast<size_t>(
2482 std::upper_bound(first1 + left_offset, last1,
2483 first2[next_right], comp) - first1)
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
2494 parallel_detail::merge_sequential(left_begin, left_end,
2495 right_begin, right_end,
2499 left_offset = next_left;
2500 right_offset = next_right;
2504 for (
auto & fut: futures)
2507 parallel_detail::throw_if_canceled(
options.cancel_token);
2508 return d_first + total;
2541 template <
typename F,
typename... Args>
2544 return [func = std::forward<F>(f),
2545 args_tuple = std::make_tuple(std::forward<Args>(args)...)]()
mutable
2547 return std::apply([&func](
auto &&... a)
2549 return std::invoke(std::move(func), std::forward<
decltype(a)>(a)...);
2550 }, std::move(args_tuple));
2556 std::exception_ptr first_exception;
2557 for (
auto & task: tasks_)
2565 if (first_exception ==
nullptr)
2566 first_exception = std::current_exception();
2570 if (propagate and first_exception !=
nullptr)
2571 std::rethrow_exception(first_exception);
2593 template <
typename F,
typename... Args>
2596 auto invocable = make_invocable(std::forward<F>(f), std::forward<Args>(args)...);
2597 tasks_.push_back(pool_->
enqueue([invocable = std::move(invocable)]()
mutable
2599 if constexpr (std::is_void_v<std::invoke_result_t<decltype(invocable) &>>)
2602 static_cast<void>(invocable());
2607 template <
typename F,
typename... Args>
2610 launch(std::forward<F>(f), std::forward<Args>(args)...);
2617 [[nodiscard]]
size_t size() const noexcept {
return tasks_.size(); }
2620 [[nodiscard]]
bool is_empty() const noexcept {
return tasks_.empty(); }
size_t size_t int32_t * out
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_
~ConditionVariableRegistration()
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_
std::condition_variable * cv_
ConditionVariableRegistration(ConditionVariableRegistration &&other) noexcept
void unregister() 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.
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.
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)
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.
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
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.
void next()
Advance all underlying iterators (bounds-checked).
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.
static struct argp_option options[]
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)
std::mutex observer_mutex
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 ~TaskBase()=default
Virtual destructor.
Concrete task implementation with type preservation.
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.