40#include <gtest/gtest.h>
44#include <condition_variable>
60using namespace std::chrono_literals;
97 auto future = pool.
enqueue([] {
return 42; });
99 EXPECT_EQ(future.get(), 42);
106 auto future = pool.
enqueue([](
int a,
int b) {
return a + b; }, 10, 20);
108 EXPECT_EQ(future.get(), 30);
118 EXPECT_EQ(future.get(), 200);
124 std::atomic<bool> executed{
false};
126 auto future = pool.
enqueue([&executed] { executed =
true; });
129 EXPECT_TRUE(executed);
135 const int num_tasks = 100;
136 std::vector<std::future<int>> futures;
138 for (
int i = 0; i < num_tasks; ++i)
139 futures.push_back(pool.
enqueue([i] { return i * i; }));
141 for (
int i = 0; i < num_tasks; ++i)
142 EXPECT_EQ(futures[i].get(), i * i);
148 auto token = source.token();
150 EXPECT_FALSE(token.stop_requested());
151 source.request_cancel();
152 EXPECT_TRUE(token.stop_requested());
162 auto state = std::make_shared<CancellationState>();
167 std::condition_variable first, filler, last;
168 state->register_condition_variable(&first);
169 for (
int i = 0; i < 1'000'000; ++i)
170 state->register_condition_variable(&filler);
171 state->register_condition_variable(&last);
172 for (
int i = 0; i < 1'000'000; ++i)
173 state->register_condition_variable(&filler);
174 std::optional<CancellationToken::ConditionVariableRegistration> guard;
175 guard.emplace(state, &last);
177 std::atomic<bool> notifying{
true};
179 bool late_notification =
false;
180 std::thread waiter([&] {
181 std::unique_lock<std::mutex> lock(mutex);
182 while (not state->stop_requested.load())
183 first.wait_for(lock, 1ms);
187 late_notification = last.wait_for(lock, 200ms) == std::cv_status::no_timeout
188 and notifying.load();
191 state->stop_requested.store(
true);
192 state->notify_observers();
193 notifying.store(
false);
195 EXPECT_FALSE(late_notification);
200#if defined(_MSC_VER) && !defined(__clang__)
201# pragma warning(push)
202# pragma warning(disable : 4996)
204# pragma GCC diagnostic push
205# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
212 for (
int round = 0; round < 20; ++round)
215 const auto token = source.token();
216 std::atomic<int> ready{0};
217 std::vector<std::thread> threads;
218 for (
int t = 0; t < 4; ++t)
219 threads.emplace_back([&] {
221 while (not token.stop_requested())
223 auto cv = std::make_unique<std::condition_variable>();
224 auto guard = token.notify_on_cancel(*cv);
230 while (ready.load() < 4)
231 std::this_thread::yield();
232 source.request_cancel();
233 for (
auto & thread : threads)
238#if defined(_MSC_VER) && !defined(__clang__)
241# pragma GCC diagnostic pop
250 const std::chrono::milliseconds time)
252 std::unique_lock<std::mutex> lock(mutex);
253 std::atomic<bool> started{
false}, finished{
false};
254 std::thread canceller([&] {
256 source.request_cancel();
257 finished.store(
true);
259 while (not started.load())
260 std::this_thread::yield();
261 const auto deadline = std::chrono::steady_clock::now() + time;
262 while (not finished.load()
and std::chrono::steady_clock::now() < deadline)
263 std::this_thread::sleep_for(1ms);
264 const bool done = finished.load();
277 const auto token = source.token();
279 std::condition_variable cv;
281 std::unique_lock<std::mutex> lock(mutex);
282 registration = token.notify_on_cancel(cv, mutex);
283 ASSERT_FALSE(token.stop_requested());
285 std::atomic<bool> finished{
false};
286 std::thread canceller([&] {
287 source.request_cancel();
288 finished.store(
true);
290 while (not token.stop_requested())
291 std::this_thread::yield();
293 std::this_thread::sleep_for(50ms);
294 EXPECT_FALSE(finished.load());
298 EXPECT_TRUE(finished.load());
309 const auto token = source.token();
311 std::condition_variable cv;
312 std::thread canceller;
315 std::unique_lock<std::mutex> lock(mutex);
316 registration = token.notify_on_cancel(cv, mutex);
317 ASSERT_FALSE(token.stop_requested());
319 canceller = std::thread([&] { source.request_cancel(); });
320 while (not token.stop_requested())
321 std::this_thread::yield();
322 EXPECT_EQ(cv.wait_for(lock, 10s), std::cv_status::no_timeout)
323 <<
"the cancellation did not wake up the waiter";
336 const auto token = source.token();
337 std::mutex first_mutex, second_mutex;
338 std::condition_variable first_cv, second_cv;
339 auto first = token.notify_on_cancel(first_cv, first_mutex);
340 auto second = token.notify_on_cancel(second_cv, second_mutex);
342 std::unique_lock<std::mutex> lock(first_mutex);
343 std::thread canceller([&] { source.request_cancel(); });
344 while (not token.stop_requested())
345 std::this_thread::yield();
346 std::this_thread::sleep_for(50ms);
348 std::promise<void> ended;
349 auto future = ended.get_future();
350 std::thread ender([&] {
354 const bool done = future.wait_for(10s) == std::future_status::ready;
358 EXPECT_TRUE(done) <<
"ending a registration waited for the mutex of another one";
369 const auto token = source.token();
371 std::condition_variable cv;
372 auto first = token.notify_on_cancel(cv, mutex);
373 auto second = token.notify_on_cancel(cv, mutex);
376 EXPECT_FALSE(cancellation_finishes_within(source, mutex, 50ms))
377 <<
"ending the first registration ended the second one";
379 auto moved = std::move(second);
381 EXPECT_FALSE(cancellation_finishes_within(source, mutex, 50ms))
382 <<
"ending the moved-from guard ended its registration";
385 EXPECT_TRUE(cancellation_finishes_within(source, mutex, 10'000ms))
386 <<
"a registration remained";
388 auto late = token.notify_on_cancel(cv, mutex);
389 EXPECT_TRUE(cancellation_finishes_within(source, mutex, 10'000ms))
390 <<
"a registration was made after the cancellation";
400 const auto token = source.token();
402 std::condition_variable cv;
404 auto constructed_from = token.notify_on_cancel(cv, mutex);
405 auto constructed = std::move(constructed_from);
407 auto again = std::move(constructed_from);
409 auto assigned_from = token.notify_on_cancel(cv, mutex);
411 assigned = std::move(assigned_from);
413 assigned = std::move(assigned_from);
415 EXPECT_TRUE(cancellation_finishes_within(source, mutex, 10'000ms))
416 <<
"a registration remained";
425 for (
int round = 0; round < 20; ++round)
428 const auto token = source.token();
429 std::atomic<int> ready{0};
430 std::vector<std::thread> threads;
431 for (
int t = 0; t < 4; ++t)
432 threads.emplace_back([&, t] {
434 while (not token.stop_requested())
436 auto mutex = std::make_unique<std::mutex>();
437 auto cv = std::make_unique<std::condition_variable>();
439 CancellationToken::ConditionVariableRegistration guard;
440 std::unique_lock<std::mutex> lock(*mutex);
441 guard = token.notify_on_cancel(*cv, *mutex);
443 (void) cv->wait_for(lock, 1ms, [&] { return token.stop_requested(); });
450 while (ready.load() < 4)
451 std::this_thread::yield();
452 source.request_cancel();
453 for (
auto & thread : threads)
462 std::atomic<int>
sum{0};
464 for (
int i = 1; i <= 8; ++i)
465 group.
launch([&
sum, i] { sum.fetch_add(i, std::memory_order_relaxed); });
467 EXPECT_EQ(group.
size(), 8u);
468 EXPECT_NO_THROW(group.
wait());
469 EXPECT_EQ(
sum.load(), 36);
483 throw std::logic_error(
"boom");
489 EXPECT_THROW(group.
wait(), std::logic_error);
498 std::atomic<size_t> processed{0};
503 options.cancel_token = source.token();
508 source.request_cancel();
513 EXPECT_LT(processed.load(), 1024u);
519 std::atomic<int>
sum{0};
522 [&] {
sum.fetch_add(1, std::memory_order_relaxed); },
523 [&] {
sum.fetch_add(10, std::memory_order_relaxed); },
524 [&] {
sum.fetch_add(100, std::memory_order_relaxed); });
526 EXPECT_EQ(
sum.load(), 111);
536 [] {
throw std::runtime_error(
"parallel_invoke boom"); },
548 options.cancel_token = source.token();
549 source.request_cancel();
560 std::vector<int> input(1024);
561 std::iota(input.begin(), input.end(), 1);
562 std::vector<int>
output(input.size());
563 std::vector<int>
expected(input.size());
565 std::partial_sum(input.begin(), input.end(),
expected.begin());
566 pscan(pool, input.begin(), input.end(),
output.begin(), std::plus<int>{});
574 std::vector<int> input = {3, 1, 4, 1, 5, 9};
575 std::vector<int>
output(input.size());
581 EXPECT_EQ(
output, (std::vector<int>{3, 4, 8, 9, 14, 23}));
587 std::vector<int> input = {1, 2, 3, 4, 5};
588 std::vector<int>
output(input.size());
591 EXPECT_EQ(
output, (std::vector<int>{0, 1, 3, 6, 10}));
597 std::vector<int> input(2048, 1);
598 std::vector<int>
output(input.size());
603 options.cancel_token = source.token();
604 source.request_cancel();
606 EXPECT_THROW(
pscan(input.begin(), input.end(),
output.begin(),
614 std::vector<int> left(500), right(700), merged(1200),
expected(1200);
615 std::iota(left.begin(), left.end(), 0);
616 std::iota(right.begin(), right.end(), 250);
618 std::merge(left.begin(), left.end(), right.begin(), right.end(),
expected.begin());
619 pmerge(pool, left.begin(), left.end(), right.begin(), right.end(), merged.begin());
627 std::vector<int> left = {9, 7, 5, 3, 1};
628 std::vector<int> right = {10, 8, 6, 4, 2};
629 std::vector<int> merged(left.size() + right.size());
634 pmerge(left.begin(), left.end(), right.begin(), right.end(),
635 merged.begin(), std::greater<int>{},
options);
637 EXPECT_EQ(merged, (std::vector<int>{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}));
643 std::vector<int> left(1024), right(1024), merged(2048);
644 std::iota(left.begin(), left.end(), 0);
645 std::iota(right.begin(), right.end(), 0);
650 options.cancel_token = source.token();
651 source.request_cancel();
653 EXPECT_THROW(
pmerge(left.begin(), left.end(), right.begin(), right.end(),
654 merged.begin(), std::less<int>{},
options),
665 std::vector<int> input,
output;
666 pscan(pool, input.begin(), input.end(),
output.begin(), std::plus<int>{});
667 EXPECT_TRUE(
output.empty());
672 EXPECT_TRUE(
output.empty());
678 std::vector<int> input = {42};
679 std::vector<int>
output(1);
680 pscan(pool, input.begin(), input.end(),
output.begin(), std::plus<int>{});
681 EXPECT_EQ(
output, (std::vector<int>{42}));
687 EXPECT_EQ(
output, (std::vector<int>{42}));
693 std::vector<int> input,
output;
695 EXPECT_TRUE(
output.empty());
700 EXPECT_TRUE(
output.empty());
706 std::vector<int> input = {7};
707 std::vector<int>
output(1);
709 EXPECT_EQ(
output, (std::vector<int>{0}));
715 EXPECT_EQ(
output, (std::vector<int>{0}));
721 std::vector<int> left, right = {1, 2, 3};
722 std::vector<int> merged(right.size());
723 pmerge(pool, left.begin(), left.end(), right.begin(), right.end(), merged.begin());
724 EXPECT_EQ(merged, right);
728 std::fill(merged.begin(), merged.end(), 0);
729 pmerge(left.begin(), left.end(), right.begin(), right.end(),
730 merged.begin(), std::less<int>{},
options);
731 EXPECT_EQ(merged, right);
737 std::vector<int> left = {1, 2, 3}, right;
738 std::vector<int> merged(left.size());
739 pmerge(pool, left.begin(), left.end(), right.begin(), right.end(), merged.begin());
740 EXPECT_EQ(merged, left);
744 std::fill(merged.begin(), merged.end(), 0);
745 pmerge(left.begin(), left.end(), right.begin(), right.end(),
746 merged.begin(), std::less<int>{},
options);
747 EXPECT_EQ(merged, left);
753 std::vector<int> left, right, merged;
754 pmerge(pool, left.begin(), left.end(), right.begin(), right.end(), merged.begin());
755 EXPECT_TRUE(merged.empty());
759 pmerge(left.begin(), left.end(), right.begin(), right.end(),
760 merged.begin(), std::less<int>{},
options);
761 EXPECT_TRUE(merged.empty());
767 std::vector<long long> scan_input(200000);
768 std::iota(scan_input.begin(), scan_input.end(), 1LL);
769 std::vector<long long> scan_output(scan_input.size());
771 auto scan_start = std::chrono::high_resolution_clock::now();
772 pscan(pool, scan_input.begin(), scan_input.end(), scan_output.begin(), std::plus<long long>{});
773 auto scan_end = std::chrono::high_resolution_clock::now();
775 std::vector<int> left(100000), right(100000), merged(200000);
776 std::iota(left.begin(), left.end(), 0);
777 std::iota(right.begin(), right.end(), 50000);
779 auto merge_start = std::chrono::high_resolution_clock::now();
780 pmerge(pool, left.begin(), left.end(), right.begin(), right.end(), merged.begin());
781 auto merge_end = std::chrono::high_resolution_clock::now();
783 auto scan_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
784 scan_end - scan_start).count();
785 auto merge_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
786 merge_end - merge_start).count();
788 EXPECT_TRUE(std::is_sorted(merged.begin(), merged.end()));
789 EXPECT_EQ(scan_output.back(),
790 std::accumulate(scan_input.begin(), scan_input.end(), 0
LL));
792 std::cout <<
"\n=== Benchmark: pscan / pmerge ===\n";
793 std::cout <<
"pscan(200K): " << scan_ms <<
" ms\n";
794 std::cout <<
"pmerge(200K): " << merge_ms <<
" ms\n";
795 std::cout <<
"=================================\n\n";
805 std::atomic<bool> block{
true};
808 pool.
enqueue_detached([&block] {
while (block) std::this_thread::yield(); });
811 for (
int i = 0; i < 5; ++i)
828 auto f1 = pool.
enqueue([] {
return 1; });
829 auto f2 = pool.
enqueue([] {
return 2; });
847 for (
int i = 0; i < 10; ++i)
861 EXPECT_THROW(pool.
enqueue([] { return 0; }), std::runtime_error);
884 auto future = pool.
enqueue([] {
return 42; });
885 EXPECT_EQ(future.get(), 42);
897 auto future = pool.
enqueue([] {
return 42; });
898 EXPECT_EQ(future.get(), 42);
913 EXPECT_THROW(pool.
resize(4), std::runtime_error);
919 std::atomic<bool> block{
true};
923 pool.
enqueue_detached([&block] {
while (block) std::this_thread::yield(); });
926 for (
int i = 0; i < 5; ++i)
947 auto future = pool.
enqueue([] {
948 throw std::runtime_error(
"test exception");
952 EXPECT_THROW(future.get(), std::runtime_error);
960 throw std::runtime_error(
"test");
964 auto f2 = pool.
enqueue([] {
return 42; });
966 EXPECT_THROW(f1.get(), std::runtime_error);
967 EXPECT_EQ(f2.get(), 42);
978 const int tasks_per_thread = 100;
979 const int num_enqueue_threads = 4;
981 std::vector<std::thread> enqueuers;
982 for (
int t = 0; t < num_enqueue_threads; ++t)
984 enqueuers.emplace_back([&pool, &
counter, tasks_per_thread] {
985 for (
int i = 0; i < tasks_per_thread; ++i)
990 for (
auto& t : enqueuers)
995 EXPECT_EQ(
counter.load(), tasks_per_thread * num_enqueue_threads);
1001 std::atomic<int> concurrent_count{0};
1002 std::atomic<int> max_concurrent{0};
1004 std::vector<std::future<void>> futures;
1005 for (
int i = 0; i < 100; ++i)
1007 futures.push_back(pool.
enqueue([&concurrent_count, &max_concurrent] {
1008 int current = ++concurrent_count;
1011 int prev_max = max_concurrent.load();
1012 while (current > prev_max &&
1013 !max_concurrent.compare_exchange_weak(prev_max, current))
1016 std::this_thread::sleep_for(1ms);
1021 for (
auto& f : futures)
1025 EXPECT_GT(max_concurrent.load(), 1);
1035 const size_t num_threads = 8;
1037 std::condition_variable all_started;
1039 std::atomic<size_t> met{0};
1040 const auto deadline = std::chrono::steady_clock::now() + 30s;
1045 for (
size_t i = 0; i < num_threads; ++i)
1047 std::unique_lock<std::mutex> lock(m);
1048 if (++started == num_threads)
1049 all_started.notify_all();
1050 if (all_started.wait_until(lock, deadline,
1051 [&] { return started == num_threads; }))
1056 EXPECT_EQ(met.load(), num_threads);
1065 ThreadPool pool(std::thread::hardware_concurrency());
1066 const int num_tasks = 10000;
1067 std::atomic<int>
sum{0};
1069 auto start = std::chrono::high_resolution_clock::now();
1071 std::vector<std::future<void>> futures;
1072 futures.reserve(num_tasks);
1074 for (
int i = 0; i < num_tasks; ++i)
1075 futures.push_back(pool.
enqueue([&
sum, i] { sum += i; }));
1077 for (
auto& f : futures)
1080 auto end = std::chrono::high_resolution_clock::now();
1081 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
1084 int expected = num_tasks * (num_tasks - 1) / 2;
1088 EXPECT_LT(duration.count(), 5000);
1093 ThreadPool pool(std::thread::hardware_concurrency());
1094 const int num_tasks = 100;
1097 auto compute = [](
int n) {
1099 for (
int i = 0; i < n; ++i)
1100 sum += std::sqrt(
static_cast<double>(i));
1104 std::vector<std::future<double>> futures;
1105 for (
int i = 0; i < num_tasks; ++i)
1106 futures.push_back(pool.
enqueue(compute, 10000));
1108 for (
auto& f : futures)
1112 const auto start = std::chrono::steady_clock::now();
1114 std::chrono::steady_clock::now() - start < 1s)
1116 std::this_thread::sleep_for(1ms);
1130 auto future = pool.
enqueue([] {
return std::string(
"hello"); });
1132 EXPECT_EQ(future.get(),
"hello");
1139 auto future = pool.
enqueue([] {
1140 return std::vector<int>{1, 2, 3, 4, 5};
1143 auto result = future.get();
1144 EXPECT_EQ(result.size(), 5u);
1145 EXPECT_EQ(result[2], 3);
1152 auto future = pool.
enqueue([](
int a,
int b) {
1153 return std::make_pair(a + b, a * b);
1179 EXPECT_EQ(future.get(), 42);
1187 auto future = pool.
enqueue(f, 32);
1189 EXPECT_EQ(future.get(), 42);
1195 std::function<int(
int)> func = [](
int x) {
return x * x; };
1197 auto future = pool.
enqueue(func, 6);
1199 EXPECT_EQ(future.get(), 36);
1223 EXPECT_EQ(future.get(), 42);
1231 auto future = pool.
enqueue(&Calculator::multiply, &calc, 6, 7);
1233 EXPECT_EQ(future.get(), 42);
1240 auto future = pool.
enqueue(&Calculator::square, 7);
1242 EXPECT_EQ(future.get(), 49);
1254 EXPECT_EQ(future.get(), 42);
1265 auto ptr = std::make_unique<int>(42);
1266 auto future = pool.
enqueue([p = std::move(ptr)]() {
return *p; });
1268 EXPECT_EQ(future.get(), 42);
1275 auto ptr = std::make_unique<int>(100);
1276 auto future = pool.
enqueue([](std::unique_ptr<int> p) {
return *p * 2; },
1279 EXPECT_EQ(future.get(), 200);
1286 struct MoveOnlyFunctor
1288 std::unique_ptr<int> data;
1290 MoveOnlyFunctor(
int v) : data(std::make_unique<int>(v)) {}
1291 MoveOnlyFunctor(MoveOnlyFunctor&&) =
default;
1292 MoveOnlyFunctor& operator=(MoveOnlyFunctor&&) =
default;
1293 MoveOnlyFunctor(
const MoveOnlyFunctor&) =
delete;
1295 int operator()() {
return *data; }
1298 auto future = pool.
enqueue(MoveOnlyFunctor{42});
1300 EXPECT_EQ(future.get(), 42);
1312 for (
int i = 0; i < 10; ++i)
1317 EXPECT_EQ(
counter.load(), 10);
1323 std::atomic<int>
sum{0};
1325 for (
int i = 1; i <= 5; ++i)
1330 EXPECT_EQ(
sum.load(), 15);
1362 std::vector<int> inputs = {1, 2, 3, 4, 5};
1364 auto futures = pool.
enqueue_bulk([](
int x) {
return x * x; }, inputs);
1366 ASSERT_EQ(futures.size(), 5u);
1367 EXPECT_EQ(futures[0].get(), 1);
1368 EXPECT_EQ(futures[1].get(), 4);
1369 EXPECT_EQ(futures[2].get(), 9);
1370 EXPECT_EQ(futures[3].get(), 16);
1371 EXPECT_EQ(futures[4].get(), 25);
1377 std::vector<std::string> inputs = {
"hello",
"world",
"test"};
1379 auto futures = pool.
enqueue_bulk([](
const std::string& s) {
1383 ASSERT_EQ(futures.size(), 3u);
1384 EXPECT_EQ(futures[0].get(), 5u);
1385 EXPECT_EQ(futures[1].get(), 5u);
1386 EXPECT_EQ(futures[2].get(), 4u);
1392 std::vector<int> empty;
1394 auto futures = pool.
enqueue_bulk([](
int x) {
return x; }, empty);
1396 EXPECT_TRUE(futures.empty());
1407 EXPECT_GT(pool.num_threads(), 0u);
1408 EXPECT_FALSE(pool.is_stopped());
1415 EXPECT_EQ(future.get(), 42);
1423 EXPECT_EQ(&pool1, &pool2);
1441 EXPECT_EQ(
value, 11);
1452 EXPECT_EQ(
value, 150);
1458 const int value = 77;
1460 auto future = pool.
enqueue([](
const int& x) {
return x * 2; }, std::cref(
value));
1462 EXPECT_EQ(future.get(), 154);
1473 EXPECT_EQ(
value, 42);
1484 EXPECT_EQ(future.get(), 42);
1496 for (
int i = 0; i < 10; ++i)
1498 std::this_thread::sleep_for(10ms);
1504 EXPECT_EQ(
counter.load(), 10);
1524 ThreadPool pool(std::thread::hardware_concurrency());
1525 const int num_tasks = 100000;
1528 for (
int i = 0; i < num_tasks; ++i)
1533 EXPECT_EQ(
counter.load(), num_tasks);
1539 const int num_enqueuers = 16;
1540 const int tasks_per_enqueuer = 1000;
1543 std::vector<std::thread> enqueuers;
1544 for (
int i = 0; i < num_enqueuers; ++i)
1546 enqueuers.emplace_back([&pool, &
counter, tasks_per_enqueuer] {
1547 for (
int j = 0; j < tasks_per_enqueuer; ++j)
1552 for (
auto& t : enqueuers)
1557 EXPECT_EQ(
counter.load(), num_enqueuers * tasks_per_enqueuer);
1563 std::atomic<int> fast_count{0};
1564 std::atomic<int> slow_count{0};
1567 for (
int i = 0; i < 100; ++i)
1571 std::this_thread::sleep_for(1ms);
1578 EXPECT_EQ(fast_count.load(), 100);
1579 EXPECT_EQ(slow_count.load(), 100);
1589 std::vector<int> results;
1593 for (
int i = 0; i < 10; ++i)
1596 std::lock_guard<std::mutex> lock(mtx);
1597 results.push_back(i);
1603 EXPECT_EQ(results.size(), 10u);
1610 for (
int i = 0; i < 1000; ++i)
1622 auto future = pool.
enqueue([] {
1623 std::vector<int> large(10000);
1624 std::iota(large.begin(), large.end(), 0);
1628 auto result = future.get();
1629 EXPECT_EQ(result.size(), 10000u);
1630 EXPECT_EQ(result[9999], 9999);
1637 auto future = pool.
enqueue([&pool] {
1639 return pool.
enqueue([] {
return 42; });
1642 auto inner_future = future.get();
1643 EXPECT_EQ(inner_future.get(), 42);
1651 std::function<void(
int)> recursive = [&pool, &
counter, &recursive](
int depth) {
1660 std::this_thread::sleep_for(100ms);
1663 EXPECT_EQ(
counter.load(), 11);
1670 auto f1 = pool.
enqueue([]() ->
int {
throw std::runtime_error(
"runtime"); });
1671 auto f2 = pool.
enqueue([]() ->
int {
throw std::logic_error(
"logic"); });
1672 auto f3 = pool.
enqueue([]() ->
int {
throw std::out_of_range(
"range"); });
1673 auto f4 = pool.
enqueue([] {
return 42; });
1675 EXPECT_THROW(f1.get(), std::runtime_error);
1676 EXPECT_THROW(f2.get(), std::logic_error);
1677 EXPECT_THROW(f3.get(), std::out_of_range);
1678 EXPECT_EQ(f4.get(), 42);
1684 std::atomic<int> exception_count{0};
1686 std::vector<std::future<int>> futures;
1687 for (
int i = 0; i < 100; ++i)
1689 futures.push_back(pool.
enqueue([]() ->
int {
1690 throw std::runtime_error(
"test");
1694 for (
auto& f : futures)
1700 catch (
const std::runtime_error&)
1706 EXPECT_EQ(exception_count.load(), 100);
1716 std::atomic<int> started{0};
1717 std::atomic<int> finished{0};
1718 std::atomic<bool> can_finish{
false};
1721 for (
int i = 0; i < 4; ++i)
1726 std::this_thread::sleep_for(1ms);
1733 std::this_thread::sleep_for(1ms);
1741 EXPECT_EQ(finished.load(), 4);
1750 for (
int i = 0; i < 10; ++i)
1753 std::this_thread::sleep_for(10ms);
1760 EXPECT_EQ(
counter.load(), 10);
1767 std::atomic<bool> keep_running{
true};
1768 std::atomic<bool> resize_in_progress{
false};
1771 std::thread producer([&pool, &
counter, &keep_running, &resize_in_progress] {
1772 while (keep_running)
1775 if (!resize_in_progress)
1781 catch (
const std::runtime_error&)
1786 std::this_thread::sleep_for(1ms);
1791 std::this_thread::sleep_for(20ms);
1792 resize_in_progress =
true;
1794 resize_in_progress =
false;
1795 std::this_thread::sleep_for(20ms);
1796 resize_in_progress =
true;
1798 resize_in_progress =
false;
1799 std::this_thread::sleep_for(20ms);
1801 keep_running =
false;
1815 const int num_tasks = 10000;
1816 std::vector<std::future<int>> futures;
1817 futures.reserve(num_tasks);
1820 for (
int i = 0; i < num_tasks; ++i)
1821 futures.push_back(pool.
enqueue([i] { return i; }));
1824 for (
int i = 0; i < num_tasks; ++i)
1825 EXPECT_EQ(futures[i].get(), i);
1831 std::atomic<long long>
sum{0};
1832 const int num_tasks = 10000;
1834 for (
int i = 1; i <= num_tasks; ++i)
1840 long long expected =
static_cast<long long>(num_tasks) * (num_tasks + 1) / 2;
1847 std::vector<int> shared_vec;
1849 const int num_tasks = 1000;
1851 for (
int i = 0; i < num_tasks; ++i)
1854 std::lock_guard<std::mutex> lock(mtx);
1855 shared_vec.push_back(i);
1861 EXPECT_EQ(shared_vec.size(),
static_cast<size_t>(num_tasks));
1864 std::sort(shared_vec.begin(), shared_vec.end());
1865 for (
int i = 0; i < num_tasks; ++i)
1866 EXPECT_EQ(shared_vec[i], i);
1875 const int num_tasks = 100;
1876 const auto work_duration = 10ms;
1878 auto do_work = [work_duration] {
1879 std::this_thread::sleep_for(work_duration);
1884 auto start_single = std::chrono::high_resolution_clock::now();
1885 for (
int i = 0; i < num_tasks; ++i)
1888 auto end_single = std::chrono::high_resolution_clock::now();
1889 auto duration_single = std::chrono::duration_cast<std::chrono::milliseconds>(end_single - start_single);
1892 size_t num_threads = std::min(8u, std::thread::hardware_concurrency());
1894 auto start_parallel = std::chrono::high_resolution_clock::now();
1895 for (
int i = 0; i < num_tasks; ++i)
1898 auto end_parallel = std::chrono::high_resolution_clock::now();
1899 auto duration_parallel = std::chrono::duration_cast<std::chrono::milliseconds>(end_parallel - start_parallel);
1902 double speedup =
static_cast<double>(duration_single.count()) / duration_parallel.count();
1903 EXPECT_GT(speedup, 1.5);
1909 const int num_tasks = 1000;
1911 auto start = std::chrono::high_resolution_clock::now();
1913 std::vector<std::future<int>> futures;
1914 futures.reserve(num_tasks);
1915 for (
int i = 0; i < num_tasks; ++i)
1916 futures.push_back(pool.
enqueue([i] { return i; }));
1919 for (
auto& f : futures)
1922 auto end = std::chrono::high_resolution_clock::now();
1923 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
1928 EXPECT_EQ(
sum,
static_cast<long long>(num_tasks) * (num_tasks - 1) / 2);
1929 std::cout <<
" [" << num_tasks <<
" trivial tasks: "
1930 << duration.count() / 1000.0 <<
" ms]\n";
1941 auto outer = [](
int x) {
1947 auto future = pool.
enqueue([outer] {
1948 auto inner = outer(10);
1952 EXPECT_EQ(future.get(), 42);
1959 auto add = [](
int a,
int b,
int c) {
return a + b + c; };
1960 auto bound = std::bind(add, 10, std::placeholders::_1, 20);
1962 auto future = pool.
enqueue(bound, 12);
1964 EXPECT_EQ(future.get(), 42);
1972 auto generic_add = [](
auto a,
auto b) {
return a + b; };
1974 auto future_int = pool.
enqueue(generic_add, 20, 22);
1975 auto future_double = pool.
enqueue(generic_add, 20.5, 21.5);
1977 EXPECT_EQ(future_int.get(), 42);
1978 EXPECT_DOUBLE_EQ(future_double.get(), 42.0);
1985 std::vector<int> large_data(1000, 42);
1987 auto future = pool.
enqueue([data = std::move(large_data)]()
mutable {
1988 return std::accumulate(data.begin(), data.end(), 0);
1991 EXPECT_EQ(future.get(), 42000);
2002 auto sum_all = [](
int a,
int b,
int c,
int d,
int e,
2003 int f,
int g,
int h,
int i,
int j) {
2004 return a + b + c + d + e + f + g +
h + i + j;
2007 auto future = pool.
enqueue(sum_all, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
2009 EXPECT_EQ(future.get(), 55);
2019 std::queue<int> work_queue;
2020 std::mutex queue_mutex;
2021 std::condition_variable cv;
2022 std::atomic<bool> done{
false};
2023 std::atomic<int> consumed{0};
2027 for (
int i = 0; i < 100; ++i)
2030 std::lock_guard<std::mutex> lock(queue_mutex);
2034 std::this_thread::sleep_for(1ms);
2041 for (
int c = 0; c < 3; ++c)
2047 std::unique_lock<std::mutex> lock(queue_mutex);
2048 cv.wait_for(lock, 10ms, [&] {
return !work_queue.empty() || done; });
2049 if (work_queue.empty() && done)
2051 if (work_queue.empty())
2062 EXPECT_EQ(consumed.load(), 100);
2076 EXPECT_EQ(soft, 100u);
2077 EXPECT_EQ(hard, 500u);
2087 EXPECT_EQ(soft, 100u);
2088 EXPECT_EQ(hard, 1000u);
2097 std::vector<std::future<int>> futures;
2098 for (
int i = 0; i < 50; ++i)
2101 for (
int i = 0; i < 50; ++i)
2102 EXPECT_EQ(futures[i].get(), i);
2110 std::atomic<bool> worker_blocked{
true};
2111 std::atomic<int> enqueued{0};
2115 while (worker_blocked)
2116 std::this_thread::sleep_for(1ms);
2120 for (
int i = 0; i < 5; ++i)
2128 std::atomic<bool> enqueue_completed{
false};
2129 std::thread blocker([&pool, &enqueue_completed] {
2131 enqueue_completed =
true;
2135 std::this_thread::sleep_for(50ms);
2136 EXPECT_FALSE(enqueue_completed);
2139 worker_blocked =
false;
2145 EXPECT_TRUE(enqueue_completed);
2153 std::atomic<bool> worker_blocked{
true};
2157 while (worker_blocked)
2158 std::this_thread::sleep_for(1ms);
2162 for (
int i = 0; i < 15; ++i)
2169 worker_blocked =
false;
2178 std::atomic<bool> worker_blocked{
true};
2180 while (worker_blocked)
2181 std::this_thread::sleep_for(1ms);
2185 for (
int i = 0; i < 10; ++i)
2191 FAIL() <<
"Expected queue_overflow_error";
2197 EXPECT_NE(std::string(e.what()).find(
"overflow"), std::string::npos);
2200 worker_blocked =
false;
2209 std::atomic<bool> worker_blocked{
true};
2211 while (worker_blocked)
2212 std::this_thread::sleep_for(1ms);
2216 for (
int i = 0; i < 3; ++i)
2220 std::atomic<bool> done{
false};
2221 std::thread t([&pool, &done] {
2226 std::this_thread::sleep_for(30ms);
2229 worker_blocked =
false;
2242 EXPECT_THROW(pool.
enqueue_bounded([] { return 0; }), std::runtime_error);
2251 std::atomic<int> produced{0};
2252 std::atomic<int> consumed{0};
2253 std::atomic<bool> stop_producing{
false};
2256 auto consume = [&consumed] {
2257 std::this_thread::sleep_for(5ms);
2262 std::thread producer([&] {
2263 while (!stop_producing && produced < 50)
2279 std::this_thread::sleep_for(200ms);
2280 stop_producing =
true;
2286 EXPECT_EQ(consumed.load(), produced.load());
2295 const int num_producers = 8;
2296 const int tasks_per_producer = 100;
2298 std::vector<std::thread> producers;
2299 for (
int p = 0; p < num_producers; ++p)
2301 producers.emplace_back([&pool, &
counter, tasks_per_producer] {
2302 for (
int i = 0; i < tasks_per_producer; ++i)
2311 std::this_thread::sleep_for(1ms);
2318 for (
auto& t : producers)
2323 EXPECT_EQ(
counter.load(), num_producers * tasks_per_producer);
2331 std::vector<std::future<int>> futures;
2332 for (
int i = 0; i < 100; ++i)
2335 for (
int i = 0; i < 100; ++i)
2336 EXPECT_EQ(futures[i].get(), i * i);
2345 throw std::runtime_error(
"test");
2348 EXPECT_THROW(future.get(), std::runtime_error);
2359 for (
int i = 0; i < 100; ++i)
2378 EXPECT_EQ(
counter.load(), 100);
2387 const int num_tasks = 10000;
2389 for (
int i = 0; i < num_tasks; ++i)
2392 bool success =
false;
2402 std::this_thread::sleep_for(100us);
2408 EXPECT_EQ(
counter.load(), num_tasks);
2420 EXPECT_EQ(soft, std::numeric_limits<size_t>::max());
2421 EXPECT_EQ(hard, std::numeric_limits<size_t>::max());
2433 EXPECT_EQ(future.get(), 42);
2445 EXPECT_EQ(future.get(), 20);
2446 EXPECT_EQ(
value, 20);
2458 auto result = pool.
try_enqueue([] {
return 42; });
2460 ASSERT_TRUE(result.has_value());
2461 EXPECT_EQ(result->get(), 42);
2469 std::atomic<bool> worker_blocked{
true};
2471 while (worker_blocked)
2472 std::this_thread::sleep_for(1ms);
2476 for (
int i = 0; i < 5; ++i)
2481 EXPECT_FALSE(result.has_value());
2483 worker_blocked =
false;
2495 EXPECT_TRUE(success);
2505 std::atomic<bool> worker_blocked{
true};
2507 while (worker_blocked)
2508 std::this_thread::sleep_for(1ms);
2512 for (
int i = 0; i < 3; ++i)
2517 EXPECT_FALSE(success);
2519 worker_blocked =
false;
2528 EXPECT_THROW(pool.
try_enqueue([] { return 0; }), std::runtime_error);
2537 auto result = pool.
try_enqueue([](
int a,
int b) {
return a + b; }, 20, 22);
2539 ASSERT_TRUE(result.has_value());
2540 EXPECT_EQ(result->get(), 42);
2548 std::atomic<bool> worker_blocked{
true};
2550 while (worker_blocked)
2551 std::this_thread::sleep_for(1ms);
2562 for (
int i = 0; i < 1000; ++i)
2563 if (not pool.
try_enqueue([] { return 0; }).has_value())
2565 EXPECT_EQ(refused, 1000);
2567 worker_blocked =
false;
2579#if defined(__linux__) && defined(CPU_COUNT)
2581 if (sched_getaffinity(0,
sizeof(set), &set) == 0)
2582 return static_cast<size_t>(CPU_COUNT(&set));
2584 return std::max(1u, std::thread::hardware_concurrency());
2589 const int num_tasks = 1000;
2590 const auto work_duration = 100us;
2592 auto do_work = [work_duration] {
2593 auto start = std::chrono::high_resolution_clock::now();
2594 while (std::chrono::high_resolution_clock::now() - start < work_duration)
2600 auto seq_start = std::chrono::high_resolution_clock::now();
2602 for (
int i = 0; i < num_tasks; ++i)
2603 seq_sum += do_work();
2604 auto seq_end = std::chrono::high_resolution_clock::now();
2605 auto seq_duration = std::chrono::duration_cast<std::chrono::milliseconds>(seq_end - seq_start);
2609 size_t num_threads = std::min<size_t>(
usable_cpus(), 8);
2618 auto pool_duration = std::chrono::milliseconds::max();
2619 for (
int attempt = 0; attempt < 3; ++attempt)
2621 auto pool_start = std::chrono::high_resolution_clock::now();
2622 std::vector<std::future<int>> futures;
2623 futures.reserve(num_tasks);
2624 for (
int i = 0; i < num_tasks; ++i)
2625 futures.push_back(pool.
enqueue(do_work));
2628 for (
auto& f : futures)
2629 pool_sum += f.get();
2630 auto pool_end = std::chrono::high_resolution_clock::now();
2631 pool_duration = std::min(pool_duration,
2632 std::chrono::duration_cast<std::chrono::milliseconds>(pool_end - pool_start));
2635 EXPECT_EQ(seq_sum, pool_sum);
2637 double speedup =
static_cast<double>(seq_duration.count()) / pool_duration.count();
2639 std::cout <<
"\n=== Benchmark: ThreadPool vs Sequential ===\n";
2640 std::cout <<
"Tasks: " << num_tasks <<
", Work per task: 100μs\n";
2641 std::cout <<
"Threads: " << num_threads <<
"\n";
2642 std::cout <<
"Sequential: " << seq_duration.count() <<
" ms\n";
2643 std::cout <<
"ThreadPool: " << pool_duration.count() <<
" ms\n";
2644 std::cout <<
"Speedup: " << std::fixed << std::setprecision(2) << speedup <<
"x\n";
2645 std::cout <<
"============================================\n\n";
2651 const int num_tasks = 100000;
2654 auto start = std::chrono::high_resolution_clock::now();
2655 for (
int i = 0; i < num_tasks; ++i)
2658 auto end = std::chrono::high_resolution_clock::now();
2660 auto total_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
2661 double ns_per_task =
static_cast<double>(total_ns) / num_tasks;
2663 std::cout <<
"\n=== Benchmark: Enqueue Overhead ===\n";
2664 std::cout <<
"Tasks: " << num_tasks <<
"\n";
2665 std::cout <<
"Total time: " << total_ns / 1000000.0 <<
" ms\n";
2666 std::cout <<
"Per task: " << std::fixed << std::setprecision(0) << ns_per_task <<
" ns\n";
2667 std::cout <<
"Throughput: " << std::fixed << std::setprecision(0)
2668 << (num_tasks * 1e9 / total_ns) <<
" tasks/sec\n";
2669 std::cout <<
"===================================\n\n";
2673 EXPECT_LT(ns_per_task, 25000);
2678 const int num_tasks = 500;
2680 auto compute = [](
int x) ->
long long {
2682 for (
int i = 0; i < 1000; ++i)
2683 sum +=
static_cast<long long>(i) * x;
2691 const size_t num_threads = std::min<size_t>(
usable_cpus(), 8);
2692 const int batch =
static_cast<int>(num_threads);
2693 auto async_start = std::chrono::high_resolution_clock::now();
2694 std::vector<std::future<long long>> async_futures;
2695 async_futures.reserve(num_threads);
2696 long long async_sum = 0;
2697 for (
int first = 0; first < num_tasks; first += batch)
2699 const int last = std::min(num_tasks, first + batch);
2700 async_futures.clear();
2701 for (
int i = first; i < last; ++i)
2702 async_futures.push_back(std::async(std::launch::async, compute, i));
2703 for (
auto& f : async_futures)
2704 async_sum += f.get();
2706 auto async_end = std::chrono::high_resolution_clock::now();
2707 auto async_duration = std::chrono::duration_cast<std::chrono::microseconds>(async_end - async_start);
2712 auto pool_start = std::chrono::high_resolution_clock::now();
2713 std::vector<std::future<long long>> pool_futures;
2714 pool_futures.reserve(num_tasks);
2715 for (
int i = 0; i < num_tasks; ++i)
2716 pool_futures.push_back(pool.
enqueue(compute, i));
2718 long long pool_sum = 0;
2719 for (
auto& f : pool_futures)
2720 pool_sum += f.get();
2721 auto pool_end = std::chrono::high_resolution_clock::now();
2722 auto pool_duration = std::chrono::duration_cast<std::chrono::microseconds>(pool_end - pool_start);
2724 EXPECT_EQ(async_sum, pool_sum);
2726 double speedup =
static_cast<double>(async_duration.count()) / pool_duration.count();
2730 std::cout <<
"\n=== Benchmark: ThreadPool vs std::async ===\n";
2731 std::cout <<
"Tasks: " << num_tasks <<
", Threads: " << num_threads <<
"\n";
2732 std::cout <<
"std::async: " << async_duration.count() / 1000.0 <<
" ms\n";
2733 std::cout <<
"ThreadPool: " << pool_duration.count() / 1000.0 <<
" ms\n";
2734 std::cout <<
"Speedup: " << std::fixed << std::setprecision(2) << speedup <<
"x\n";
2735 std::cout <<
"============================================\n\n";
2749 EXPECT_EQ(stats.tasks_completed, 0u);
2750 EXPECT_EQ(stats.tasks_failed, 0u);
2751 EXPECT_EQ(stats.current_queue_size, 0u);
2752 EXPECT_EQ(stats.current_active, 0u);
2753 EXPECT_EQ(stats.num_workers, 2u);
2754 EXPECT_EQ(stats.peak_queue_size, 0u);
2755 EXPECT_EQ(stats.total_processed(), 0u);
2762 std::vector<std::future<int>> futures;
2763 for (
int i = 0; i < 10; ++i)
2764 futures.push_back(pool.
enqueue([] { return 42; }));
2766 for (
auto& f : futures)
2772 EXPECT_EQ(stats.tasks_completed, 10u);
2773 EXPECT_EQ(stats.total_processed(), 10u);
2781 std::promise<void> blocker;
2782 pool.
enqueue([&blocker] { blocker.get_future().wait(); });
2785 for (
int i = 0; i < 5; ++i)
2788 std::this_thread::sleep_for(std::chrono::milliseconds(10));
2791 EXPECT_GE(stats.peak_queue_size, 5u);
2794 blocker.set_value();
2802 pool.
enqueue([] {
return 1; }).get();
2807 EXPECT_GE(stats1.tasks_completed, 1u);
2812 EXPECT_EQ(stats2.tasks_completed, 0u);
2813 EXPECT_EQ(stats2.peak_queue_size, 0u);
2822 std::atomic<bool> callback_called{
false};
2823 std::atomic<bool> correct_exception{
false};
2826 callback_called =
true;
2828 std::rethrow_exception(ep);
2829 }
catch (
const std::runtime_error& e) {
2830 correct_exception = (std::string(e.what()) ==
"test error");
2832 correct_exception =
false;
2837 throw std::runtime_error(
"test error");
2841 std::this_thread::sleep_for(std::chrono::milliseconds(50));
2843 EXPECT_TRUE(callback_called.load());
2844 EXPECT_TRUE(correct_exception.load());
2851 std::atomic<int> callback_count{0};
2859 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2861 EXPECT_EQ(callback_count.load(), 1);
2868 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2871 EXPECT_EQ(callback_count.load(), 1);
2883 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2886 EXPECT_EQ(stats.tasks_failed, 2u);
2887 EXPECT_EQ(stats.tasks_completed, 1u);
2888 EXPECT_EQ(stats.total_processed(), 3u);
2897 pool.
enqueue([] {
return 42; }).get();
2899 bool result = pool.
wait_all_for(std::chrono::milliseconds(100));
2900 EXPECT_TRUE(result);
2909 std::this_thread::sleep_for(std::chrono::milliseconds(500));
2912 std::this_thread::sleep_for(std::chrono::milliseconds(10));
2914 bool result = pool.
wait_all_for(std::chrono::milliseconds(50));
2915 EXPECT_FALSE(result);
2925 pool.
enqueue([] {
return 1; }).get();
2927 auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(100);
2929 EXPECT_TRUE(result);
2938 std::vector<std::tuple<int, int>> args = {
2939 {1, 2}, {3, 4}, {5, 6}, {7, 8}
2942 auto futures = pool.
enqueue_batch([](
int a,
int b) {
return a + b; }, args);
2944 EXPECT_EQ(futures.size(), 4u);
2946 std::vector<int> results;
2947 for (
auto& f : futures)
2948 results.push_back(f.get());
2950 EXPECT_EQ(results, (std::vector<int>{3, 7, 11, 15}));
2957 std::vector<std::tuple<int>> args;
2958 for (
int i = 0; i < 100; ++i)
2959 args.emplace_back(i);
2961 auto futures = pool.
enqueue_batch([](
int x) {
return x * x; }, args);
2964 for (
auto& f : futures)
2968 EXPECT_EQ(
sum, 328350);
2975 std::vector<std::tuple<int>> empty;
2976 auto futures = pool.
enqueue_batch([](
int x) {
return x; }, empty);
2978 EXPECT_TRUE(futures.empty());
2987 std::vector<int> data(100, 1);
2989 parallel_for(pool, data.begin(), data.end(), [](
int& x) { x *= 2; });
2999 std::vector<int> data(100, 1);
3002 [](
auto begin,
auto end) {
3003 for (auto it = begin; it != end; ++it)
3015 std::vector<int> empty;
3018 parallel_for(pool, empty.begin(), empty.end(), [](
int& x) { x = 0; });
3020 EXPECT_TRUE(empty.empty());
3027 std::vector<std::atomic<int>> data(50);
3028 for (
auto& x : data)
3032 [](std::atomic<int>& x) { ++x; },
3035 for (
const auto& x : data)
3036 EXPECT_EQ(x.load(), 1);
3045 std::vector<int> data(100, 0);
3048 data[i] = static_cast<int>(i * 2);
3051 for (
size_t i = 0; i < data.size(); ++i)
3052 EXPECT_EQ(data[i],
static_cast<int>(i * 2));
3070 std::vector<int> input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
3071 std::vector<int>
output(10);
3074 [](
int x) { return x * x; });
3076 EXPECT_EQ(
output, (std::vector<int>{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}));
3083 std::vector<int> input(1000);
3084 std::iota(input.begin(), input.end(), 0);
3086 std::vector<int>
output(1000);
3089 [](
int x) { return x + 1; });
3091 for (
int i = 0; i < 1000; ++i)
3092 EXPECT_EQ(
output[i], i + 1);
3099 std::vector<int> input;
3103 output.begin(), [](
int x) { return x; });
3105 EXPECT_EQ(end,
output.begin());
3114 std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
3125 std::vector<int> data = {1, 2, 3, 4, 5};
3128 std::multiplies<int>());
3137 std::vector<int> data = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
3140 std::numeric_limits<int>::min(),
3141 [](
int a,
int b) { return std::max(a, b); });
3143 EXPECT_EQ(max_val, 9);
3150 std::vector<long long> data(10000);
3151 std::iota(data.begin(), data.end(), 1LL);
3154 std::plus<long long>());
3157 EXPECT_EQ(
sum, 50005000LL);
3164 std::vector<int> empty;
3169 EXPECT_EQ(result, 42);
3182 EXPECT_NEAR(stats.
queue_utilization(std::numeric_limits<size_t>::max()), 0.0, 0.01);
3187 ::testing::InitGoogleTest(&argc, argv);
3188 return RUN_ALL_TESTS();
size_t size_t int32_t value
Cooperative cancellation source paired with CancellationToken.
RAII guard for condition variable cancellation registration.
Minimal structured-concurrency helper over ThreadPool futures.
bool is_empty() const noexcept
Return true if the group has no pending tasks.
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.
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.
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.
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.
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.
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.
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.
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.
Minimal std::expected-style result type for C++20.
Exception thrown when cooperative cancellation is observed.
Exception thrown when the task queue exceeds its hard limit.
size_t current_size() const noexcept
Current queue size when exception was thrown.
size_t hard_limit() const noexcept
Hard limit that was exceeded.
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.
bool completed() const noexcept
Return true if all underlying iterators are finished.
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.
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.
T product(const Container &container, const T &init=T{1})
Compute product of all elements.
auto pscan(ThreadPool &pool, const Container &c, BinaryOp op, size_t chunk_size=0)
Parallel inclusive scan over a container.
void parallel_invoke(ThreadPool &pool, Fs &&... fs)
Invoke a small set of related callables in parallel.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Basic arithmetic operations for the calculator.
double add(double a, double b)
static struct argp_option options[]
Common configuration object for parallel algorithms.
ThreadPool * pool
Executor to use (nullptr = default_pool()).
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.
int multiply(int a, int b) const
int operator()(int x) const
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
A modern, efficient thread pool for parallel task execution.
void increment_ref(int &x)
TEST_F(ThreadPoolTest, DefaultConstruction)
static size_t usable_cpus()
void add_to_ref(int &x, int amount)