Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
thread_pool_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
33
40#include <gtest/gtest.h>
41#include <thread_pool.H>
42#include <atomic>
43#include <chrono>
44#include <condition_variable>
45#include <future>
46#include <memory>
47#include <mutex>
48#include <optional>
49#include <thread>
50#include <vector>
51#include <cmath>
52#include <numeric>
53#include <iomanip>
54#include <algorithm>
55#if defined(__linux__)
56# include <sched.h>
57#endif
58
59using namespace Aleph;
60using namespace std::chrono_literals;
61
62class ThreadPoolTest : public ::testing::Test
63{
64protected:
65 void SetUp() override {}
66 void TearDown() override {}
67};
68
69// ============================================================================
70// Basic Functionality Tests
71// ============================================================================
72
73TEST_F(ThreadPoolTest, DefaultConstruction)
74{
75 ThreadPool pool;
76 EXPECT_GT(pool.num_threads(), 0u);
77 EXPECT_TRUE(pool.is_idle());
78 EXPECT_FALSE(pool.is_stopped());
79}
80
81TEST_F(ThreadPoolTest, ConstructionWithSize)
82{
83 ThreadPool pool(4);
84 EXPECT_EQ(pool.num_threads(), 4u);
85}
86
87TEST_F(ThreadPoolTest, ConstructionWithZeroDefaultsToOne)
88{
89 ThreadPool pool(0);
90 EXPECT_GE(pool.num_threads(), 1u);
91}
92
94{
95 ThreadPool pool(2);
96
97 auto future = pool.enqueue([] { return 42; });
98
99 EXPECT_EQ(future.get(), 42);
100}
101
102TEST_F(ThreadPoolTest, TaskWithArguments)
103{
104 ThreadPool pool(2);
105
106 auto future = pool.enqueue([](int a, int b) { return a + b; }, 10, 20);
107
108 EXPECT_EQ(future.get(), 30);
109}
110
111TEST_F(ThreadPoolTest, TaskWithReferenceCapture)
112{
113 ThreadPool pool(2);
114 int value = 100;
115
116 auto future = pool.enqueue([&value] { return value * 2; });
117
118 EXPECT_EQ(future.get(), 200);
119}
120
122{
123 ThreadPool pool(2);
124 std::atomic<bool> executed{false};
125
126 auto future = pool.enqueue([&executed] { executed = true; });
127 future.get();
128
129 EXPECT_TRUE(executed);
130}
131
132TEST_F(ThreadPoolTest, MultipleTasks)
133{
134 ThreadPool pool(4);
135 const int num_tasks = 100;
136 std::vector<std::future<int>> futures;
137
138 for (int i = 0; i < num_tasks; ++i)
139 futures.push_back(pool.enqueue([i] { return i * i; }));
140
141 for (int i = 0; i < num_tasks; ++i)
142 EXPECT_EQ(futures[i].get(), i * i);
143}
144
145TEST_F(ThreadPoolTest, CancellationSourceAndToken)
146{
147 CancellationSource source;
148 auto token = source.token();
149
150 EXPECT_FALSE(token.stop_requested());
151 source.request_cancel();
152 EXPECT_TRUE(token.stop_requested());
153 EXPECT_THROW(token.throw_if_cancellation_requested(), operation_canceled);
154}
155
156// Once its guard is gone, a condition variable is no longer notified, so it
157// may be destroyed. The cancellation used to notify a copy of the list after
158// releasing its lock, and so it could notify a condition variable whose guard
159// was already gone.
160TEST_F(ThreadPoolTest, CancellationGuardEndsTheNotifications)
161{
162 auto state = std::make_shared<CancellationState>();
163
164 // notifying the fillers keeps the cancellation busy before the last
165 // condition variable, while its guard is destroyed, and after it, while a
166 // late notification wakes up its waiter
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);
176
177 std::atomic<bool> notifying{true};
178 std::mutex mutex;
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);
184 guard.reset();
185 // a wake-up while the cancellation still notifies is a late notification;
186 // once it has finished, a wake-up can only be spurious
187 late_notification = last.wait_for(lock, 200ms) == std::cv_status::no_timeout
188 and notifying.load();
189 });
190
191 state->stop_requested.store(true);
192 state->notify_observers();
193 notifying.store(false);
194 waiter.join();
195 EXPECT_FALSE(late_notification);
196}
197
198// notify_on_cancel(cv) is deprecated, but supported until 8.0.0; this test is
199// its coverage.
200#if defined(_MSC_VER) && !defined(__clang__)
201# pragma warning(push)
202# pragma warning(disable : 4996)
203#else
204# pragma GCC diagnostic push
205# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
206#endif
207
208// Guards come and go in several threads, each one destroying its condition
209// variable right after its guard, while the source is cancelled.
210TEST_F(ThreadPoolTest, CancellationWhileGuardsComeAndGo)
211{
212 for (int round = 0; round < 20; ++round)
213 {
214 CancellationSource source;
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([&] {
220 ++ready;
221 while (not token.stop_requested())
222 {
223 auto cv = std::make_unique<std::condition_variable>();
224 auto guard = token.notify_on_cancel(*cv);
225 guard = {};
226 cv.reset();
227 }
228 });
229
230 while (ready.load() < 4)
231 std::this_thread::yield();
232 source.request_cancel();
233 for (auto & thread : threads)
234 thread.join();
235 }
236}
237
238#if defined(_MSC_VER) && !defined(__clang__)
239# pragma warning(pop)
240#else
241# pragma GCC diagnostic pop
242#endif
243
244namespace
245{
246 // Requests the cancellation of source while holding mutex, and tells
247 // whether it finished within time. While a registration of the mutex
248 // remains, the cancellation waits for the mutex and cannot finish.
249 bool cancellation_finishes_within(CancellationSource & source, std::mutex & mutex,
250 const std::chrono::milliseconds time)
251 {
252 std::unique_lock<std::mutex> lock(mutex);
253 std::atomic<bool> started{false}, finished{false};
254 std::thread canceller([&] {
255 started.store(true);
256 source.request_cancel();
257 finished.store(true);
258 });
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();
265 lock.unlock();
266 canceller.join();
267 return done;
268 }
269}
270
271// A cancellation takes the mutex of a registration made with one before it
272// notifies the condition variable, so it does not finish while a waiter
273// holds the mutex, between its check of the token and its wait.
274TEST_F(ThreadPoolTest, ExactCancellationTakesTheRegisteredMutex)
275{
276 CancellationSource source;
277 const auto token = source.token();
278 std::mutex mutex;
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());
284
285 std::atomic<bool> finished{false};
286 std::thread canceller([&] {
287 source.request_cancel();
288 finished.store(true);
289 });
290 while (not token.stop_requested())
291 std::this_thread::yield();
292 // the pause only gives a cancellation that does not wait the time to finish
293 std::this_thread::sleep_for(50ms);
294 EXPECT_FALSE(finished.load());
295
296 lock.unlock();
297 canceller.join();
298 EXPECT_TRUE(finished.load());
299}
300
301// The waiter checks the token and then waits without checking it again, so
302// only the notification can end its wait. The cancellation comes in between;
303// without the mutex registered, its notification came before the wait and
304// was lost. A spurious wake-up would also end the wait: this test cannot fail
305// with the notification delivered, but such a wake-up could hide a lost one.
306TEST_F(ThreadPoolTest, ExactCancellationWakesAWaiterBetweenCheckAndWait)
307{
308 CancellationSource source;
309 const auto token = source.token();
310 std::mutex mutex;
311 std::condition_variable cv;
312 std::thread canceller;
313 {
315 std::unique_lock<std::mutex> lock(mutex);
316 registration = token.notify_on_cancel(cv, mutex);
317 ASSERT_FALSE(token.stop_requested());
318
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";
324 }
325 canceller.join();
326}
327
328// A thread holds the mutex of one registration while another thread ends a
329// second registration of the same source, and the cancellation waits for the
330// first mutex. A cancellation that waited for the mutex while holding the lock
331// of the registrations, which ending one needs, would wait for that thread,
332// and with one thread doing both, the two would wait for each other.
333TEST_F(ThreadPoolTest, EndingARegistrationDoesNotWaitForAnotherMutex)
334{
335 CancellationSource source;
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);
341
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); // so that it waits for the first mutex
347
348 std::promise<void> ended;
349 auto future = ended.get_future();
350 std::thread ender([&] {
351 second = {};
352 ended.set_value();
353 });
354 const bool done = future.wait_for(10s) == std::future_status::ready;
355 lock.unlock(); // lets everything finish, in any case
356 ender.join();
357 canceller.join();
358 EXPECT_TRUE(done) << "ending a registration waited for the mutex of another one";
359}
360
361// Each call makes its own registration, and a guard moved to another one
362// takes it along: ending one leaves the others in place. A registration
363// requested after the cancellation is empty. Whether a cancellation finishes
364// while the mutex is held shows whether a registration remains; the short
365// time only gives a wrong one the chance to finish.
366TEST_F(ThreadPoolTest, ExactRegistrationsEndOneByOne)
367{
368 CancellationSource source;
369 const auto token = source.token();
370 std::mutex mutex;
371 std::condition_variable cv;
372 auto first = token.notify_on_cancel(cv, mutex);
373 auto second = token.notify_on_cancel(cv, mutex);
374
375 first = {};
376 EXPECT_FALSE(cancellation_finishes_within(source, mutex, 50ms))
377 << "ending the first registration ended the second one";
378
379 auto moved = std::move(second);
380 second = {};
381 EXPECT_FALSE(cancellation_finishes_within(source, mutex, 50ms))
382 << "ending the moved-from guard ended its registration";
383
384 moved = {};
385 EXPECT_TRUE(cancellation_finishes_within(source, mutex, 10'000ms))
386 << "a registration remained";
387
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";
391}
392
393// A guard moved to another one is left empty, so it can be moved again after
394// the other one has ended the registration. It used to keep the position of
395// the registration, which ending it invalidates, and moving it again copied
396// that position; debug iterators catch it.
397TEST_F(ThreadPoolTest, MovedFromGuardCanBeMovedAgain)
398{
399 CancellationSource source;
400 const auto token = source.token();
401 std::mutex mutex;
402 std::condition_variable cv;
403
404 auto constructed_from = token.notify_on_cancel(cv, mutex);
405 auto constructed = std::move(constructed_from);
406 constructed = {};
407 auto again = std::move(constructed_from);
408
409 auto assigned_from = token.notify_on_cancel(cv, mutex);
411 assigned = std::move(assigned_from);
412 assigned = {};
413 assigned = std::move(assigned_from);
414
415 EXPECT_TRUE(cancellation_finishes_within(source, mutex, 10'000ms))
416 << "a registration remained";
417}
418
419// Guards come and go in several threads, while the source is cancelled. Each
420// thread destroys its condition variable and its mutex right after its guard,
421// some after waiting on them, so a cancellation that used them later would be
422// caught by the sanitizers.
423TEST_F(ThreadPoolTest, ExactCancellationWhileGuardsComeAndGo)
424{
425 for (int round = 0; round < 20; ++round)
426 {
427 CancellationSource source;
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] {
433 ++ready;
434 while (not token.stop_requested())
435 {
436 auto mutex = std::make_unique<std::mutex>();
437 auto cv = std::make_unique<std::condition_variable>();
438 {
439 CancellationToken::ConditionVariableRegistration guard;
440 std::unique_lock<std::mutex> lock(*mutex);
441 guard = token.notify_on_cancel(*cv, *mutex);
442 if (t % 2 == 1)
443 (void) cv->wait_for(lock, 1ms, [&] { return token.stop_requested(); });
444 }
445 cv.reset();
446 mutex.reset();
447 }
448 });
449
450 while (ready.load() < 4)
451 std::this_thread::yield();
452 source.request_cancel();
453 for (auto & thread : threads)
454 thread.join();
455 }
456}
457
458TEST_F(ThreadPoolTest, TaskGroupWaitsForAllTasks)
459{
460 ThreadPool pool(4);
461 TaskGroup group(pool);
462 std::atomic<int> sum{0};
463
464 for (int i = 1; i <= 8; ++i)
465 group.launch([&sum, i] { sum.fetch_add(i, std::memory_order_relaxed); });
466
467 EXPECT_EQ(group.size(), 8u);
468 EXPECT_NO_THROW(group.wait());
469 EXPECT_EQ(sum.load(), 36);
470 EXPECT_TRUE(group.is_empty());
471}
472
473TEST_F(ThreadPoolTest, TaskGroupPropagatesExceptions)
474{
475 ThreadPool pool(2);
476 TaskGroup group(pool);
477 std::atomic<int> completed{0};
478
479 group.launch([&completed] {
480 ++completed;
481 });
482 group.launch([] {
483 throw std::logic_error("boom");
484 });
485 group.launch([&completed] {
486 ++completed;
487 });
488
489 EXPECT_THROW(group.wait(), std::logic_error);
490 EXPECT_EQ(completed.load(), 2);
491 EXPECT_TRUE(group.is_empty());
492}
493
494TEST_F(ThreadPoolTest, ParallelForIndexHonorsCancellation)
495{
496 ThreadPool pool(4);
497 CancellationSource source;
498 std::atomic<size_t> processed{0};
499
501 options.pool = &pool;
502 options.chunk_size = 16;
503 options.cancel_token = source.token();
504
505 EXPECT_THROW(parallel_for_index(0, 1024,
506 [&](size_t i) {
507 if (i == 64)
508 source.request_cancel();
509 ++processed;
510 },
511 options),
513 EXPECT_LT(processed.load(), 1024u);
514}
515
516TEST_F(ThreadPoolTest, ParallelInvokeRunsAllTasks)
517{
518 ThreadPool pool(4);
519 std::atomic<int> sum{0};
520
521 parallel_invoke(pool,
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); });
525
526 EXPECT_EQ(sum.load(), 111);
527}
528
529TEST_F(ThreadPoolTest, ParallelInvokePropagatesExceptions)
530{
531 ThreadPool pool(3);
532 std::atomic<int> completed{0};
533
534 EXPECT_THROW(parallel_invoke(pool,
535 [&] { ++completed; },
536 [] { throw std::runtime_error("parallel_invoke boom"); },
537 [&] { ++completed; }),
538 std::runtime_error);
539 EXPECT_EQ(completed.load(), 2);
540}
541
542TEST_F(ThreadPoolTest, ParallelInvokeHonorsCancellation)
543{
544 ThreadPool pool(2);
545 CancellationSource source;
547 options.pool = &pool;
548 options.cancel_token = source.token();
549 source.request_cancel();
550
551 EXPECT_THROW(parallel_invoke(options,
552 [] {},
553 [] {}),
555}
556
557TEST_F(ThreadPoolTest, PscanMatchesPartialSum)
558{
559 ThreadPool pool(4);
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());
564
565 std::partial_sum(input.begin(), input.end(), expected.begin());
566 pscan(pool, input.begin(), input.end(), output.begin(), std::plus<int>{});
567
568 EXPECT_EQ(output, expected);
569}
570
571TEST_F(ThreadPoolTest, PscanAcceptsParallelOptions)
572{
573 ThreadPool pool(4);
574 std::vector<int> input = {3, 1, 4, 1, 5, 9};
575 std::vector<int> output(input.size());
577 options.pool = &pool;
578 options.chunk_size = 2;
579
580 pscan(input.begin(), input.end(), output.begin(), std::plus<int>{}, options);
581 EXPECT_EQ(output, (std::vector<int>{3, 4, 8, 9, 14, 23}));
582}
583
584TEST_F(ThreadPoolTest, PexclusiveScanMatchesSequential)
585{
586 ThreadPool pool(4);
587 std::vector<int> input = {1, 2, 3, 4, 5};
588 std::vector<int> output(input.size());
589
590 pexclusive_scan(pool, input.begin(), input.end(), output.begin(), 0, std::plus<int>{});
591 EXPECT_EQ(output, (std::vector<int>{0, 1, 3, 6, 10}));
592}
593
594TEST_F(ThreadPoolTest, PscanHonorsCancellation)
595{
596 ThreadPool pool(4);
597 std::vector<int> input(2048, 1);
598 std::vector<int> output(input.size());
599 CancellationSource source;
601 options.pool = &pool;
602 options.chunk_size = 64;
603 options.cancel_token = source.token();
604 source.request_cancel();
605
606 EXPECT_THROW(pscan(input.begin(), input.end(), output.begin(),
607 std::plus<int>{}, options),
609}
610
611TEST_F(ThreadPoolTest, PmergeMatchesStdMerge)
612{
613 ThreadPool pool(4);
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);
617
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());
620
621 EXPECT_EQ(merged, expected);
622}
623
624TEST_F(ThreadPoolTest, PmergeAcceptsParallelOptionsAndComparator)
625{
626 ThreadPool pool(4);
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());
631 options.pool = &pool;
632 options.chunk_size = 3;
633
634 pmerge(left.begin(), left.end(), right.begin(), right.end(),
635 merged.begin(), std::greater<int>{}, options);
636
637 EXPECT_EQ(merged, (std::vector<int>{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}));
638}
639
640TEST_F(ThreadPoolTest, PmergeHonorsCancellation)
641{
642 ThreadPool pool(4);
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);
646 CancellationSource source;
648 options.pool = &pool;
649 options.chunk_size = 64;
650 options.cancel_token = source.token();
651 source.request_cancel();
652
653 EXPECT_THROW(pmerge(left.begin(), left.end(), right.begin(), right.end(),
654 merged.begin(), std::less<int>{}, options),
656}
657
658// ============================================================================
659// Boundary Cases: empty / single-element
660// ============================================================================
661
662TEST_F(ThreadPoolTest, PscanEmptyInput)
663{
664 ThreadPool pool(4);
665 std::vector<int> input, output;
666 pscan(pool, input.begin(), input.end(), output.begin(), std::plus<int>{});
667 EXPECT_TRUE(output.empty());
668
670 options.pool = &pool;
671 pscan(input.begin(), input.end(), output.begin(), std::plus<int>{}, options);
672 EXPECT_TRUE(output.empty());
673}
674
675TEST_F(ThreadPoolTest, PscanSingleElement)
676{
677 ThreadPool pool(4);
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}));
682
684 options.pool = &pool;
685 std::fill(output.begin(), output.end(), 0);
686 pscan(input.begin(), input.end(), output.begin(), std::plus<int>{}, options);
687 EXPECT_EQ(output, (std::vector<int>{42}));
688}
689
690TEST_F(ThreadPoolTest, PexclusiveScanEmptyInput)
691{
692 ThreadPool pool(4);
693 std::vector<int> input, output;
694 pexclusive_scan(pool, input.begin(), input.end(), output.begin(), 0, std::plus<int>{});
695 EXPECT_TRUE(output.empty());
696
698 options.pool = &pool;
699 pexclusive_scan(input.begin(), input.end(), output.begin(), 0, std::plus<int>{}, options);
700 EXPECT_TRUE(output.empty());
701}
702
703TEST_F(ThreadPoolTest, PexclusiveScanSingleElement)
704{
705 ThreadPool pool(4);
706 std::vector<int> input = {7};
707 std::vector<int> output(1);
708 pexclusive_scan(pool, input.begin(), input.end(), output.begin(), 0, std::plus<int>{});
709 EXPECT_EQ(output, (std::vector<int>{0}));
710
712 options.pool = &pool;
713 std::fill(output.begin(), output.end(), -1);
714 pexclusive_scan(input.begin(), input.end(), output.begin(), 0, std::plus<int>{}, options);
715 EXPECT_EQ(output, (std::vector<int>{0}));
716}
717
718TEST_F(ThreadPoolTest, PmergeEmptyLeft)
719{
720 ThreadPool pool(4);
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);
725
727 options.pool = &pool;
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);
732}
733
734TEST_F(ThreadPoolTest, PmergeEmptyRight)
735{
736 ThreadPool pool(4);
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);
741
743 options.pool = &pool;
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);
748}
749
750TEST_F(ThreadPoolTest, PmergeBothEmpty)
751{
752 ThreadPool pool(4);
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());
756
758 options.pool = &pool;
759 pmerge(left.begin(), left.end(), right.begin(), right.end(),
760 merged.begin(), std::less<int>{}, options);
761 EXPECT_TRUE(merged.empty());
762}
763
764TEST_F(ThreadPoolTest, BenchmarkScanAndMerge)
765{
766 ThreadPool pool(4);
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());
770
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();
774
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);
778
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();
782
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();
787
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(), 0LL));
791
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";
796}
797
798// ============================================================================
799// Status and Query Tests
800// ============================================================================
801
802TEST_F(ThreadPoolTest, PendingTasks)
803{
804 ThreadPool pool(1);
805 std::atomic<bool> block{true};
806
807 // Block the single worker
808 pool.enqueue_detached([&block] { while (block) std::this_thread::yield(); });
809
810 // Queue more tasks
811 for (int i = 0; i < 5; ++i)
812 pool.enqueue_detached([] {});
813
814 // Should have pending tasks
815 EXPECT_GT(pool.pending_tasks(), 0u);
816
817 // Unblock
818 block = false;
819 pool.wait_all();
820
821 EXPECT_EQ(pool.pending_tasks(), 0u);
822}
823
824TEST_F(ThreadPoolTest, IsIdleAfterCompletion)
825{
826 ThreadPool pool(2);
827
828 auto f1 = pool.enqueue([] { return 1; });
829 auto f2 = pool.enqueue([] { return 2; });
830
831 f1.get();
832 f2.get();
833
834 pool.wait_all();
835 EXPECT_TRUE(pool.is_idle());
836}
837
838// ============================================================================
839// Shutdown Tests
840// ============================================================================
841
842TEST_F(ThreadPoolTest, ShutdownCompletesAllTasks)
843{
844 ThreadPool pool(2);
845 std::atomic<int> counter{0};
846
847 for (int i = 0; i < 10; ++i)
848 pool.enqueue_detached([&counter] { ++counter; });
849
850 pool.shutdown();
851
852 EXPECT_EQ(counter.load(), 10);
853 EXPECT_TRUE(pool.is_stopped());
854}
855
856TEST_F(ThreadPoolTest, EnqueueAfterShutdownThrows)
857{
858 ThreadPool pool(2);
859 pool.shutdown();
860
861 EXPECT_THROW(pool.enqueue([] { return 0; }), std::runtime_error);
862}
863
864TEST_F(ThreadPoolTest, DoubleShutdownIsSafe)
865{
866 ThreadPool pool(2);
867 pool.shutdown();
868 EXPECT_NO_THROW(pool.shutdown());
869}
870
871// ============================================================================
872// Resize Tests
873// ============================================================================
874
875TEST_F(ThreadPoolTest, ResizeIncrease)
876{
877 ThreadPool pool(2);
878 EXPECT_EQ(pool.num_threads(), 2u);
879
880 pool.resize(4);
881 EXPECT_EQ(pool.num_threads(), 4u);
882
883 // Verify new workers work
884 auto future = pool.enqueue([] { return 42; });
885 EXPECT_EQ(future.get(), 42);
886}
887
888TEST_F(ThreadPoolTest, ResizeDecrease)
889{
890 ThreadPool pool(4);
891 EXPECT_EQ(pool.num_threads(), 4u);
892
893 pool.resize(2);
894 EXPECT_EQ(pool.num_threads(), 2u);
895
896 // Verify remaining workers work
897 auto future = pool.enqueue([] { return 42; });
898 EXPECT_EQ(future.get(), 42);
899}
900
901TEST_F(ThreadPoolTest, ResizeToSameIsNoOp)
902{
903 ThreadPool pool(4);
904 pool.resize(4);
905 EXPECT_EQ(pool.num_threads(), 4u);
906}
907
908TEST_F(ThreadPoolTest, ResizeAfterShutdownThrows)
909{
910 ThreadPool pool(2);
911 pool.shutdown();
912
913 EXPECT_THROW(pool.resize(4), std::runtime_error);
914}
915
916TEST_F(ThreadPoolTest, ResizePreservesPendingTasks)
917{
918 ThreadPool pool(1);
919 std::atomic<bool> block{true};
920 std::atomic<int> completed{0};
921
922 // Block the worker
923 pool.enqueue_detached([&block] { while (block) std::this_thread::yield(); });
924
925 // Queue tasks
926 for (int i = 0; i < 5; ++i)
927 pool.enqueue_detached([&completed] { ++completed; });
928
929 // Unblock and resize
930 block = false;
931 pool.resize(4);
932
933 pool.wait_all();
934
935 // All tasks should complete (first blocking task + 5 counting tasks)
936 EXPECT_EQ(completed.load(), 5);
937}
938
939// ============================================================================
940// Exception Handling Tests
941// ============================================================================
942
943TEST_F(ThreadPoolTest, ExceptionPropagation)
944{
945 ThreadPool pool(2);
946
947 auto future = pool.enqueue([] {
948 throw std::runtime_error("test exception");
949 return 0;
950 });
951
952 EXPECT_THROW(future.get(), std::runtime_error);
953}
954
955TEST_F(ThreadPoolTest, ExceptionDoesNotAffectOtherTasks)
956{
957 ThreadPool pool(2);
958
959 auto f1 = pool.enqueue([] {
960 throw std::runtime_error("test");
961 return 0;
962 });
963
964 auto f2 = pool.enqueue([] { return 42; });
965
966 EXPECT_THROW(f1.get(), std::runtime_error);
967 EXPECT_EQ(f2.get(), 42);
968}
969
970// ============================================================================
971// Concurrency Tests
972// ============================================================================
973
974TEST_F(ThreadPoolTest, ConcurrentEnqueue)
975{
976 ThreadPool pool(4);
977 std::atomic<int> counter{0};
978 const int tasks_per_thread = 100;
979 const int num_enqueue_threads = 4;
980
981 std::vector<std::thread> enqueuers;
982 for (int t = 0; t < num_enqueue_threads; ++t)
983 {
984 enqueuers.emplace_back([&pool, &counter, tasks_per_thread] {
985 for (int i = 0; i < tasks_per_thread; ++i)
986 pool.enqueue_detached([&counter] { ++counter; });
987 });
988 }
989
990 for (auto& t : enqueuers)
991 t.join();
992
993 pool.wait_all();
994
995 EXPECT_EQ(counter.load(), tasks_per_thread * num_enqueue_threads);
996}
997
998TEST_F(ThreadPoolTest, ParallelExecution)
999{
1000 ThreadPool pool(4);
1001 std::atomic<int> concurrent_count{0};
1002 std::atomic<int> max_concurrent{0};
1003
1004 std::vector<std::future<void>> futures;
1005 for (int i = 0; i < 100; ++i)
1006 {
1007 futures.push_back(pool.enqueue([&concurrent_count, &max_concurrent] {
1008 int current = ++concurrent_count;
1009
1010 // Update max if this is higher
1011 int prev_max = max_concurrent.load();
1012 while (current > prev_max &&
1013 !max_concurrent.compare_exchange_weak(prev_max, current))
1014 ;
1015
1016 std::this_thread::sleep_for(1ms);
1017 --concurrent_count;
1018 }));
1019 }
1020
1021 for (auto& f : futures)
1022 f.get();
1023
1024 // Should have had multiple concurrent executions
1025 EXPECT_GT(max_concurrent.load(), 1);
1026}
1027
1028// Each task waits until all of them have started, which a pool that ran
1029// fewer tasks at once than it has threads would never let happen: it checks
1030// without a clock what a speedup would, and a busy machine only delays it.
1031// The deadline, far beyond what such a machine needs to start them, makes
1032// such a pool fail the test instead of hanging it
1033TEST_F(ThreadPoolTest, RunsAsManyTasksAtOnceAsItHasThreads)
1034{
1035 const size_t num_threads = 8;
1036 std::mutex m;
1037 std::condition_variable all_started;
1038 size_t started = 0;
1039 std::atomic<size_t> met{0};
1040 const auto deadline = std::chrono::steady_clock::now() + 30s;
1041 // The pool last: were an enqueue to throw, it joins its threads before
1042 // what their tasks capture by reference is destroyed
1043 ThreadPool pool(num_threads);
1044
1045 for (size_t i = 0; i < num_threads; ++i)
1046 pool.enqueue_detached([&] {
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; }))
1052 ++met;
1053 });
1054 pool.wait_all();
1055
1056 EXPECT_EQ(met.load(), num_threads);
1057}
1058
1059// ============================================================================
1060// Performance Tests (not strictly unit tests, but useful)
1061// ============================================================================
1062
1063TEST_F(ThreadPoolTest, ManySmallTasks)
1064{
1065 ThreadPool pool(std::thread::hardware_concurrency());
1066 const int num_tasks = 10000;
1067 std::atomic<int> sum{0};
1068
1069 auto start = std::chrono::high_resolution_clock::now();
1070
1071 std::vector<std::future<void>> futures;
1072 futures.reserve(num_tasks);
1073
1074 for (int i = 0; i < num_tasks; ++i)
1075 futures.push_back(pool.enqueue([&sum, i] { sum += i; }));
1076
1077 for (auto& f : futures)
1078 f.get();
1079
1080 auto end = std::chrono::high_resolution_clock::now();
1081 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
1082
1083 // Expected sum: 0 + 1 + 2 + ... + (n-1) = n*(n-1)/2
1084 int expected = num_tasks * (num_tasks - 1) / 2;
1085 EXPECT_EQ(sum.load(), expected);
1086
1087 // Should complete reasonably fast (less than 5 seconds)
1088 EXPECT_LT(duration.count(), 5000);
1089}
1090
1091TEST_F(ThreadPoolTest, ComputeIntensiveTasks)
1092{
1093 ThreadPool pool(std::thread::hardware_concurrency());
1094 const int num_tasks = 100;
1095
1096 // Compute-intensive task: calculate sum of squares
1097 auto compute = [](int n) {
1098 double sum = 0;
1099 for (int i = 0; i < n; ++i)
1100 sum += std::sqrt(static_cast<double>(i));
1101 return sum;
1102 };
1103
1104 std::vector<std::future<double>> futures;
1105 for (int i = 0; i < num_tasks; ++i)
1106 futures.push_back(pool.enqueue(compute, 10000));
1107
1108 for (auto& f : futures)
1109 f.get();
1110
1111 // Wait for pool to transition to idle state (fixes race condition in CI)
1112 const auto start = std::chrono::steady_clock::now();
1113 while (!pool.is_idle() &&
1114 std::chrono::steady_clock::now() - start < 1s)
1115 {
1116 std::this_thread::sleep_for(1ms);
1117 }
1118
1119 EXPECT_TRUE(pool.is_idle());
1120}
1121
1122// ============================================================================
1123// Return Type Tests
1124// ============================================================================
1125
1127{
1128 ThreadPool pool(2);
1129
1130 auto future = pool.enqueue([] { return std::string("hello"); });
1131
1132 EXPECT_EQ(future.get(), "hello");
1133}
1134
1136{
1137 ThreadPool pool(2);
1138
1139 auto future = pool.enqueue([] {
1140 return std::vector<int>{1, 2, 3, 4, 5};
1141 });
1142
1143 auto result = future.get();
1144 EXPECT_EQ(result.size(), 5u);
1145 EXPECT_EQ(result[2], 3);
1146}
1147
1149{
1150 ThreadPool pool(2);
1151
1152 auto future = pool.enqueue([](int a, int b) {
1153 return std::make_pair(a + b, a * b);
1154 }, 3, 4);
1155
1156 auto [sum, product] = future.get();
1157 EXPECT_EQ(sum, 7);
1158 EXPECT_EQ(product, 12);
1159}
1160
1161// ============================================================================
1162// Callable Types Tests
1163// ============================================================================
1164
1165int free_function(int x) { return x * 2; }
1166
1168{
1170 int operator()(int x) const { return x + value; }
1171};
1172
1174{
1175 ThreadPool pool(2);
1176
1177 auto future = pool.enqueue(free_function, 21);
1178
1179 EXPECT_EQ(future.get(), 42);
1180}
1181
1182TEST_F(ThreadPoolTest, FunctorObject)
1183{
1184 ThreadPool pool(2);
1185 Functor f{10};
1186
1187 auto future = pool.enqueue(f, 32);
1188
1189 EXPECT_EQ(future.get(), 42);
1190}
1191
1193{
1194 ThreadPool pool(2);
1195 std::function<int(int)> func = [](int x) { return x * x; };
1196
1197 auto future = pool.enqueue(func, 6);
1198
1199 EXPECT_EQ(future.get(), 36);
1200}
1201
1202// ============================================================================
1203// Member Function Tests
1204// ============================================================================
1205
1207{
1208 int value = 10;
1209
1210 int add(int x) { return value + x; }
1211 int multiply(int a, int b) const { return a * b; }
1212 static int square(int x) { return x * x; }
1213};
1214
1215TEST_F(ThreadPoolTest, MemberFunctionPointer)
1216{
1217 ThreadPool pool(2);
1218 Calculator calc;
1219 calc.value = 20;
1220
1221 auto future = pool.enqueue(&Calculator::add, &calc, 22);
1222
1223 EXPECT_EQ(future.get(), 42);
1224}
1225
1226TEST_F(ThreadPoolTest, ConstMemberFunction)
1227{
1228 ThreadPool pool(2);
1229 Calculator calc;
1230
1231 auto future = pool.enqueue(&Calculator::multiply, &calc, 6, 7);
1232
1233 EXPECT_EQ(future.get(), 42);
1234}
1235
1236TEST_F(ThreadPoolTest, StaticMemberFunction)
1237{
1238 ThreadPool pool(2);
1239
1240 auto future = pool.enqueue(&Calculator::square, 7);
1241
1242 EXPECT_EQ(future.get(), 49);
1243}
1244
1245TEST_F(ThreadPoolTest, MemberFunctionWithReference)
1246{
1247 ThreadPool pool(2);
1248 Calculator calc;
1249 calc.value = 30;
1250
1251 // Using reference wrapper
1252 auto future = pool.enqueue(&Calculator::add, std::ref(calc), 12);
1253
1254 EXPECT_EQ(future.get(), 42);
1255}
1256
1257// ============================================================================
1258// Move-Only Tests
1259// ============================================================================
1260
1261TEST_F(ThreadPoolTest, MoveOnlyLambda)
1262{
1263 ThreadPool pool(2);
1264
1265 auto ptr = std::make_unique<int>(42);
1266 auto future = pool.enqueue([p = std::move(ptr)]() { return *p; });
1267
1268 EXPECT_EQ(future.get(), 42);
1269}
1270
1271TEST_F(ThreadPoolTest, MoveOnlyArgument)
1272{
1273 ThreadPool pool(2);
1274
1275 auto ptr = std::make_unique<int>(100);
1276 auto future = pool.enqueue([](std::unique_ptr<int> p) { return *p * 2; },
1277 std::move(ptr));
1278
1279 EXPECT_EQ(future.get(), 200);
1280}
1281
1282TEST_F(ThreadPoolTest, MoveOnlyFunctor)
1283{
1284 ThreadPool pool(2);
1285
1286 struct MoveOnlyFunctor
1287 {
1288 std::unique_ptr<int> data;
1289
1290 MoveOnlyFunctor(int v) : data(std::make_unique<int>(v)) {}
1291 MoveOnlyFunctor(MoveOnlyFunctor&&) = default;
1292 MoveOnlyFunctor& operator=(MoveOnlyFunctor&&) = default;
1293 MoveOnlyFunctor(const MoveOnlyFunctor&) = delete;
1294
1295 int operator()() { return *data; }
1296 };
1297
1298 auto future = pool.enqueue(MoveOnlyFunctor{42});
1299
1300 EXPECT_EQ(future.get(), 42);
1301}
1302
1303// ============================================================================
1304// Enqueue Detached Tests
1305// ============================================================================
1306
1307TEST_F(ThreadPoolTest, EnqueueDetachedBasic)
1308{
1309 ThreadPool pool(2);
1310 std::atomic<int> counter{0};
1311
1312 for (int i = 0; i < 10; ++i)
1313 pool.enqueue_detached([&counter] { ++counter; });
1314
1315 pool.wait_all();
1316
1317 EXPECT_EQ(counter.load(), 10);
1318}
1319
1320TEST_F(ThreadPoolTest, EnqueueDetachedWithArgs)
1321{
1322 ThreadPool pool(2);
1323 std::atomic<int> sum{0};
1324
1325 for (int i = 1; i <= 5; ++i)
1326 pool.enqueue_detached([&sum](int x) { sum += x; }, i);
1327
1328 pool.wait_all();
1329
1330 EXPECT_EQ(sum.load(), 15); // 1+2+3+4+5
1331}
1332
1333TEST_F(ThreadPoolTest, EnqueueDetachedExceptionsSilent)
1334{
1335 ThreadPool pool(2);
1336 std::atomic<int> counter{0};
1337
1338 // This should not crash - exceptions are silently ignored
1339 pool.enqueue_detached([] { throw std::runtime_error("ignored"); });
1340 pool.enqueue_detached([&counter] { ++counter; });
1341
1342 pool.wait_all();
1343
1344 EXPECT_EQ(counter.load(), 1);
1345}
1346
1347TEST_F(ThreadPoolTest, EnqueueDetachedAfterShutdownThrows)
1348{
1349 ThreadPool pool(2);
1350 pool.shutdown();
1351
1352 EXPECT_THROW(pool.enqueue_detached([] {}), std::runtime_error);
1353}
1354
1355// ============================================================================
1356// Enqueue Bulk Tests
1357// ============================================================================
1358
1359TEST_F(ThreadPoolTest, EnqueueBulkVector)
1360{
1361 ThreadPool pool(4);
1362 std::vector<int> inputs = {1, 2, 3, 4, 5};
1363
1364 auto futures = pool.enqueue_bulk([](int x) { return x * x; }, inputs);
1365
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);
1372}
1373
1374TEST_F(ThreadPoolTest, EnqueueBulkStrings)
1375{
1376 ThreadPool pool(2);
1377 std::vector<std::string> inputs = {"hello", "world", "test"};
1378
1379 auto futures = pool.enqueue_bulk([](const std::string& s) {
1380 return s.size();
1381 }, inputs);
1382
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);
1387}
1388
1389TEST_F(ThreadPoolTest, EnqueueBulkEmpty)
1390{
1391 ThreadPool pool(2);
1392 std::vector<int> empty;
1393
1394 auto futures = pool.enqueue_bulk([](int x) { return x; }, empty);
1395
1396 EXPECT_TRUE(futures.empty());
1397}
1398
1399// ============================================================================
1400// Default Pool Tests
1401// ============================================================================
1402
1403TEST_F(ThreadPoolTest, DefaultPoolExists)
1404{
1405 auto& pool = Aleph::default_pool();
1406
1407 EXPECT_GT(pool.num_threads(), 0u);
1408 EXPECT_FALSE(pool.is_stopped());
1409}
1410
1411TEST_F(ThreadPoolTest, DefaultPoolWorks)
1412{
1413 auto future = Aleph::default_pool().enqueue([](int x) { return x * 2; }, 21);
1414
1415 EXPECT_EQ(future.get(), 42);
1416}
1417
1418TEST_F(ThreadPoolTest, DefaultPoolIsSingleton)
1419{
1420 auto& pool1 = Aleph::default_pool();
1421 auto& pool2 = Aleph::default_pool();
1422
1423 EXPECT_EQ(&pool1, &pool2);
1424}
1425
1426// ============================================================================
1427// Reference Argument Tests
1428// ============================================================================
1429
1430void increment_ref(int& x) { ++x; }
1431void add_to_ref(int& x, int amount) { x += amount; }
1432
1433TEST_F(ThreadPoolTest, ReferenceArgumentWithStdRef)
1434{
1435 ThreadPool pool(2);
1436 int value = 10;
1437
1438 auto future = pool.enqueue(increment_ref, std::ref(value));
1439 future.get();
1440
1441 EXPECT_EQ(value, 11);
1442}
1443
1444TEST_F(ThreadPoolTest, ReferenceArgumentMultipleParams)
1445{
1446 ThreadPool pool(2);
1447 int value = 100;
1448
1449 auto future = pool.enqueue(add_to_ref, std::ref(value), 50);
1450 future.get();
1451
1452 EXPECT_EQ(value, 150);
1453}
1454
1455TEST_F(ThreadPoolTest, ConstReferenceWithStdCref)
1456{
1457 ThreadPool pool(2);
1458 const int value = 77;
1459
1460 auto future = pool.enqueue([](const int& x) { return x * 2; }, std::cref(value));
1461
1462 EXPECT_EQ(future.get(), 154);
1463}
1464
1465TEST_F(ThreadPoolTest, LambdaCaptureByReference)
1466{
1467 ThreadPool pool(2);
1468 int value = 0;
1469
1470 auto future = pool.enqueue([&value](int x) { value = x; }, 42);
1471 future.get();
1472
1473 EXPECT_EQ(value, 42);
1474}
1475
1476TEST_F(ThreadPoolTest, MemberFunctionWithStdRef)
1477{
1478 ThreadPool pool(2);
1479 Calculator calc;
1480 calc.value = 30;
1481
1482 auto future = pool.enqueue(&Calculator::add, std::ref(calc), 12);
1483
1484 EXPECT_EQ(future.get(), 42);
1485}
1486
1487// ============================================================================
1488// WaitAll Tests
1489// ============================================================================
1490
1491TEST_F(ThreadPoolTest, WaitAllBlocks)
1492{
1493 ThreadPool pool(2);
1494 std::atomic<int> counter{0};
1495
1496 for (int i = 0; i < 10; ++i)
1497 pool.enqueue_detached([&counter] {
1498 std::this_thread::sleep_for(10ms);
1499 ++counter;
1500 });
1501
1502 pool.wait_all();
1503
1504 EXPECT_EQ(counter.load(), 10);
1505}
1506
1507TEST_F(ThreadPoolTest, WaitAllOnEmptyPool)
1508{
1509 ThreadPool pool(2);
1510
1511 // With nothing to wait for it returns at once. Without a clock: a wait of
1512 // no time at all succeeds only if the pool is idle already, and a
1513 // wait_all() that blocked would never end the test
1514 EXPECT_TRUE(pool.wait_all_for(0ms));
1515 pool.wait_all();
1516}
1517
1518// ============================================================================
1519// Stress Tests
1520// ============================================================================
1521
1522TEST_F(ThreadPoolTest, StressHighVolume)
1523{
1524 ThreadPool pool(std::thread::hardware_concurrency());
1525 const int num_tasks = 100000;
1526 std::atomic<int> counter{0};
1527
1528 for (int i = 0; i < num_tasks; ++i)
1529 pool.enqueue_detached([&counter] { ++counter; });
1530
1531 pool.wait_all();
1532
1533 EXPECT_EQ(counter.load(), num_tasks);
1534}
1535
1536TEST_F(ThreadPoolTest, StressConcurrentEnqueueFromManyThreads)
1537{
1538 ThreadPool pool(8);
1539 const int num_enqueuers = 16;
1540 const int tasks_per_enqueuer = 1000;
1541 std::atomic<int> counter{0};
1542
1543 std::vector<std::thread> enqueuers;
1544 for (int i = 0; i < num_enqueuers; ++i)
1545 {
1546 enqueuers.emplace_back([&pool, &counter, tasks_per_enqueuer] {
1547 for (int j = 0; j < tasks_per_enqueuer; ++j)
1548 pool.enqueue_detached([&counter] { ++counter; });
1549 });
1550 }
1551
1552 for (auto& t : enqueuers)
1553 t.join();
1554
1555 pool.wait_all();
1556
1557 EXPECT_EQ(counter.load(), num_enqueuers * tasks_per_enqueuer);
1558}
1559
1560TEST_F(ThreadPoolTest, StressMixedWorkloads)
1561{
1562 ThreadPool pool(4);
1563 std::atomic<int> fast_count{0};
1564 std::atomic<int> slow_count{0};
1565
1566 // Mix of fast and slow tasks
1567 for (int i = 0; i < 100; ++i)
1568 {
1569 pool.enqueue_detached([&fast_count] { ++fast_count; });
1570 pool.enqueue_detached([&slow_count] {
1571 std::this_thread::sleep_for(1ms);
1572 ++slow_count;
1573 });
1574 }
1575
1576 pool.wait_all();
1577
1578 EXPECT_EQ(fast_count.load(), 100);
1579 EXPECT_EQ(slow_count.load(), 100);
1580}
1581
1582// ============================================================================
1583// Edge Cases
1584// ============================================================================
1585
1586TEST_F(ThreadPoolTest, SingleThreadPool)
1587{
1588 ThreadPool pool(1);
1589 std::vector<int> results;
1590 std::mutex mtx;
1591
1592 // Tasks should execute sequentially
1593 for (int i = 0; i < 10; ++i)
1594 {
1595 pool.enqueue_detached([&results, &mtx, i] {
1596 std::lock_guard<std::mutex> lock(mtx);
1597 results.push_back(i);
1598 });
1599 }
1600
1601 pool.wait_all();
1602
1603 EXPECT_EQ(results.size(), 10u);
1604}
1605
1606TEST_F(ThreadPoolTest, EmptyTasksSequence)
1607{
1608 ThreadPool pool(4);
1609
1610 for (int i = 0; i < 1000; ++i)
1611 pool.enqueue_detached([] {});
1612
1613 pool.wait_all();
1614
1615 EXPECT_TRUE(pool.is_idle());
1616}
1617
1618TEST_F(ThreadPoolTest, VeryLargeReturnType)
1619{
1620 ThreadPool pool(2);
1621
1622 auto future = pool.enqueue([] {
1623 std::vector<int> large(10000);
1624 std::iota(large.begin(), large.end(), 0);
1625 return large;
1626 });
1627
1628 auto result = future.get();
1629 EXPECT_EQ(result.size(), 10000u);
1630 EXPECT_EQ(result[9999], 9999);
1631}
1632
1633TEST_F(ThreadPoolTest, TaskReturningTask)
1634{
1635 ThreadPool pool(2);
1636
1637 auto future = pool.enqueue([&pool] {
1638 // Enqueue from inside a task
1639 return pool.enqueue([] { return 42; });
1640 });
1641
1642 auto inner_future = future.get();
1643 EXPECT_EQ(inner_future.get(), 42);
1644}
1645
1646TEST_F(ThreadPoolTest, RecursiveEnqueue)
1647{
1648 ThreadPool pool(4);
1649 std::atomic<int> counter{0};
1650
1651 std::function<void(int)> recursive = [&pool, &counter, &recursive](int depth) {
1652 ++counter;
1653 if (depth > 0)
1654 pool.enqueue_detached(recursive, depth - 1);
1655 };
1656
1657 pool.enqueue_detached(recursive, 10);
1658
1659 // Wait a bit for all recursive tasks
1660 std::this_thread::sleep_for(100ms);
1661 pool.wait_all();
1662
1663 EXPECT_EQ(counter.load(), 11); // 0 to 10 inclusive
1664}
1665
1666TEST_F(ThreadPoolTest, TaskThrowingDifferentExceptions)
1667{
1668 ThreadPool pool(4);
1669
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; }); // Normal task
1674
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);
1679}
1680
1681TEST_F(ThreadPoolTest, AllTasksThrowExceptions)
1682{
1683 ThreadPool pool(4);
1684 std::atomic<int> exception_count{0};
1685
1686 std::vector<std::future<int>> futures;
1687 for (int i = 0; i < 100; ++i)
1688 {
1689 futures.push_back(pool.enqueue([]() -> int {
1690 throw std::runtime_error("test");
1691 }));
1692 }
1693
1694 for (auto& f : futures)
1695 {
1696 try
1697 {
1698 f.get();
1699 }
1700 catch (const std::runtime_error&)
1701 {
1702 ++exception_count;
1703 }
1704 }
1705
1706 EXPECT_EQ(exception_count.load(), 100);
1707}
1708
1709// ============================================================================
1710// Shutdown and Lifecycle Tests
1711// ============================================================================
1712
1713TEST_F(ThreadPoolTest, ShutdownWhileTasksRunning)
1714{
1715 ThreadPool pool(2);
1716 std::atomic<int> started{0};
1717 std::atomic<int> finished{0};
1718 std::atomic<bool> can_finish{false};
1719
1720 // Start some blocking tasks
1721 for (int i = 0; i < 4; ++i)
1722 {
1723 pool.enqueue_detached([&started, &finished, &can_finish] {
1724 ++started;
1725 while (!can_finish)
1726 std::this_thread::sleep_for(1ms);
1727 ++finished;
1728 });
1729 }
1730
1731 // Wait for tasks to start
1732 while (started < 2)
1733 std::this_thread::sleep_for(1ms);
1734
1735 // Allow tasks to finish
1736 can_finish = true;
1737
1738 // Shutdown should wait for all tasks
1739 pool.shutdown();
1740
1741 EXPECT_EQ(finished.load(), 4);
1742}
1743
1744TEST_F(ThreadPoolTest, DestructorWaitsForTasks)
1745{
1746 std::atomic<int> counter{0};
1747
1748 {
1749 ThreadPool pool(2);
1750 for (int i = 0; i < 10; ++i)
1751 {
1752 pool.enqueue_detached([&counter] {
1753 std::this_thread::sleep_for(10ms);
1754 ++counter;
1755 });
1756 }
1757 // Destructor should wait
1758 }
1759
1760 EXPECT_EQ(counter.load(), 10);
1761}
1762
1763TEST_F(ThreadPoolTest, ResizeUnderLoad)
1764{
1765 ThreadPool pool(2);
1766 std::atomic<int> counter{0};
1767 std::atomic<bool> keep_running{true};
1768 std::atomic<bool> resize_in_progress{false};
1769
1770 // Start continuous work
1771 std::thread producer([&pool, &counter, &keep_running, &resize_in_progress] {
1772 while (keep_running)
1773 {
1774 // Skip enqueue during resize to avoid race
1775 if (!resize_in_progress)
1776 {
1777 try
1778 {
1779 pool.enqueue_detached([&counter] { ++counter; });
1780 }
1781 catch (const std::runtime_error&)
1782 {
1783 // Pool might be stopped during resize, ignore
1784 }
1785 }
1786 std::this_thread::sleep_for(1ms);
1787 }
1788 });
1789
1790 // Resize while under load
1791 std::this_thread::sleep_for(20ms);
1792 resize_in_progress = true;
1793 pool.resize(8);
1794 resize_in_progress = false;
1795 std::this_thread::sleep_for(20ms);
1796 resize_in_progress = true;
1797 pool.resize(2);
1798 resize_in_progress = false;
1799 std::this_thread::sleep_for(20ms);
1800
1801 keep_running = false;
1802 producer.join();
1803 pool.wait_all();
1804
1805 EXPECT_GT(counter.load(), 0);
1806}
1807
1808// ============================================================================
1809// Data Integrity Tests
1810// ============================================================================
1811
1812TEST_F(ThreadPoolTest, DataIntegrityUnderConcurrency)
1813{
1814 ThreadPool pool(8);
1815 const int num_tasks = 10000;
1816 std::vector<std::future<int>> futures;
1817 futures.reserve(num_tasks);
1818
1819 // Each task returns its index
1820 for (int i = 0; i < num_tasks; ++i)
1821 futures.push_back(pool.enqueue([i] { return i; }));
1822
1823 // Verify all results are correct
1824 for (int i = 0; i < num_tasks; ++i)
1825 EXPECT_EQ(futures[i].get(), i);
1826}
1827
1828TEST_F(ThreadPoolTest, AtomicOperationsCorrectness)
1829{
1830 ThreadPool pool(8);
1831 std::atomic<long long> sum{0};
1832 const int num_tasks = 10000;
1833
1834 for (int i = 1; i <= num_tasks; ++i)
1835 pool.enqueue_detached([&sum, i] { sum += i; });
1836
1837 pool.wait_all();
1838
1839 // Sum of 1 to n = n*(n+1)/2
1840 long long expected = static_cast<long long>(num_tasks) * (num_tasks + 1) / 2;
1841 EXPECT_EQ(sum.load(), expected);
1842}
1843
1844TEST_F(ThreadPoolTest, MutexProtectedSharedState)
1845{
1846 ThreadPool pool(8);
1847 std::vector<int> shared_vec;
1848 std::mutex mtx;
1849 const int num_tasks = 1000;
1850
1851 for (int i = 0; i < num_tasks; ++i)
1852 {
1853 pool.enqueue_detached([&shared_vec, &mtx, i] {
1854 std::lock_guard<std::mutex> lock(mtx);
1855 shared_vec.push_back(i);
1856 });
1857 }
1858
1859 pool.wait_all();
1860
1861 EXPECT_EQ(shared_vec.size(), static_cast<size_t>(num_tasks));
1862
1863 // Sort and verify all values present
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);
1867}
1868
1869// ============================================================================
1870// Timing and Performance Tests
1871// ============================================================================
1872
1873TEST_F(ThreadPoolTest, ParallelSpeedup)
1874{
1875 const int num_tasks = 100;
1876 const auto work_duration = 10ms;
1877
1878 auto do_work = [work_duration] {
1879 std::this_thread::sleep_for(work_duration);
1880 };
1881
1882 // Sequential baseline (single thread)
1883 ThreadPool pool_single(1);
1884 auto start_single = std::chrono::high_resolution_clock::now();
1885 for (int i = 0; i < num_tasks; ++i)
1886 pool_single.enqueue_detached(do_work);
1887 pool_single.wait_all();
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);
1890
1891 // Parallel (multiple threads)
1892 size_t num_threads = std::min(8u, std::thread::hardware_concurrency());
1893 ThreadPool pool_parallel(num_threads);
1894 auto start_parallel = std::chrono::high_resolution_clock::now();
1895 for (int i = 0; i < num_tasks; ++i)
1896 pool_parallel.enqueue_detached(do_work);
1897 pool_parallel.wait_all();
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);
1900
1901 // Parallel should be significantly faster
1902 double speedup = static_cast<double>(duration_single.count()) / duration_parallel.count();
1903 EXPECT_GT(speedup, 1.5); // At least 1.5x speedup
1904}
1905
1906TEST_F(ThreadPoolTest, LowLatencySmallTasks)
1907{
1908 ThreadPool pool(4);
1909 const int num_tasks = 1000;
1910
1911 auto start = std::chrono::high_resolution_clock::now();
1912
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; }));
1917
1918 long long sum = 0;
1919 for (auto& f : futures)
1920 sum += f.get();
1921
1922 auto end = std::chrono::high_resolution_clock::now();
1923 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
1924
1925 // Every task ran and gave its own result. The time that the 1000 trivial
1926 // tasks took, typically far less than 100 ms, is printed and not bounded:
1927 // on a busy machine it is not that of the pool
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";
1931}
1932
1933// ============================================================================
1934// Complex Callable Tests
1935// ============================================================================
1936
1937TEST_F(ThreadPoolTest, NestedLambdas)
1938{
1939 ThreadPool pool(2);
1940
1941 auto outer = [](int x) {
1942 return [x](int y) {
1943 return x + y;
1944 };
1945 };
1946
1947 auto future = pool.enqueue([outer] {
1948 auto inner = outer(10);
1949 return inner(32);
1950 });
1951
1952 EXPECT_EQ(future.get(), 42);
1953}
1954
1955TEST_F(ThreadPoolTest, StdBindExpression)
1956{
1957 ThreadPool pool(2);
1958
1959 auto add = [](int a, int b, int c) { return a + b + c; };
1960 auto bound = std::bind(add, 10, std::placeholders::_1, 20);
1961
1962 auto future = pool.enqueue(bound, 12);
1963
1964 EXPECT_EQ(future.get(), 42);
1965}
1966
1967TEST_F(ThreadPoolTest, GenericLambda)
1968{
1969 ThreadPool pool(2);
1970
1971 // Generic lambda (C++14+)
1972 auto generic_add = [](auto a, auto b) { return a + b; };
1973
1974 auto future_int = pool.enqueue(generic_add, 20, 22);
1975 auto future_double = pool.enqueue(generic_add, 20.5, 21.5);
1976
1977 EXPECT_EQ(future_int.get(), 42);
1978 EXPECT_DOUBLE_EQ(future_double.get(), 42.0);
1979}
1980
1981TEST_F(ThreadPoolTest, CaptureByMoveInLambda)
1982{
1983 ThreadPool pool(2);
1984
1985 std::vector<int> large_data(1000, 42);
1986
1987 auto future = pool.enqueue([data = std::move(large_data)]() mutable {
1988 return std::accumulate(data.begin(), data.end(), 0);
1989 });
1990
1991 EXPECT_EQ(future.get(), 42000);
1992}
1993
1994// ============================================================================
1995// Edge Case: Very Many Arguments
1996// ============================================================================
1997
1998TEST_F(ThreadPoolTest, ManyArguments)
1999{
2000 ThreadPool pool(2);
2001
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;
2005 };
2006
2007 auto future = pool.enqueue(sum_all, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
2008
2009 EXPECT_EQ(future.get(), 55);
2010}
2011
2012// ============================================================================
2013// Producer-Consumer Pattern
2014// ============================================================================
2015
2016TEST_F(ThreadPoolTest, ProducerConsumerPattern)
2017{
2018 ThreadPool pool(4);
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};
2024
2025 // Producer task
2026 pool.enqueue_detached([&work_queue, &queue_mutex, &cv, &done] {
2027 for (int i = 0; i < 100; ++i)
2028 {
2029 {
2030 std::lock_guard<std::mutex> lock(queue_mutex);
2031 work_queue.push(i);
2032 }
2033 cv.notify_one();
2034 std::this_thread::sleep_for(1ms);
2035 }
2036 done = true;
2037 cv.notify_all();
2038 });
2039
2040 // Consumer tasks
2041 for (int c = 0; c < 3; ++c)
2042 {
2043 pool.enqueue_detached([&work_queue, &queue_mutex, &cv, &done, &consumed] {
2044 while (true)
2045 {
2046 {
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)
2050 return;
2051 if (work_queue.empty())
2052 continue;
2053 work_queue.pop(); // Consume the item
2054 }
2055 ++consumed;
2056 }
2057 });
2058 }
2059
2060 pool.wait_all();
2061
2062 EXPECT_EQ(consumed.load(), 100);
2063}
2064
2065// ============================================================================
2066// Bounded Queue Tests
2067// ============================================================================
2068
2069TEST_F(ThreadPoolTest, SetQueueLimitsBasic)
2070{
2071 ThreadPool pool(2);
2072
2073 pool.set_queue_limits(100, 500);
2074 auto [soft, hard] = pool.get_queue_limits();
2075
2076 EXPECT_EQ(soft, 100u);
2077 EXPECT_EQ(hard, 500u);
2078}
2079
2080TEST_F(ThreadPoolTest, SetQueueLimitsDefaultHard)
2081{
2082 ThreadPool pool(2);
2083
2084 pool.set_queue_limits(100); // hard should default to 10x soft
2085 auto [soft, hard] = pool.get_queue_limits();
2086
2087 EXPECT_EQ(soft, 100u);
2088 EXPECT_EQ(hard, 1000u); // 10 * 100
2089}
2090
2091TEST_F(ThreadPoolTest, EnqueueBoundedBelowSoftLimit)
2092{
2093 ThreadPool pool(4);
2094 pool.set_queue_limits(100, 1000);
2095
2096 // Should not block when below soft limit
2097 std::vector<std::future<int>> futures;
2098 for (int i = 0; i < 50; ++i)
2099 futures.push_back(pool.enqueue_bounded([i] { return i; }));
2100
2101 for (int i = 0; i < 50; ++i)
2102 EXPECT_EQ(futures[i].get(), i);
2103}
2104
2105TEST_F(ThreadPoolTest, EnqueueBoundedBlocksAtSoftLimit)
2106{
2107 ThreadPool pool(1); // Single worker
2108 pool.set_queue_limits(5, 100);
2109
2110 std::atomic<bool> worker_blocked{true};
2111 std::atomic<int> enqueued{0};
2112
2113 // Block the only worker
2114 pool.enqueue_detached([&worker_blocked] {
2115 while (worker_blocked)
2116 std::this_thread::sleep_for(1ms);
2117 });
2118
2119 // Enqueue up to soft limit (should succeed immediately)
2120 for (int i = 0; i < 5; ++i)
2121 {
2122 pool.enqueue_bounded_detached([&enqueued] { ++enqueued; });
2123 }
2124
2125 EXPECT_EQ(pool.pending_tasks(), 5u);
2126
2127 // Next enqueue should block
2128 std::atomic<bool> enqueue_completed{false};
2129 std::thread blocker([&pool, &enqueue_completed] {
2130 pool.enqueue_bounded_detached([] {});
2131 enqueue_completed = true;
2132 });
2133
2134 // Give it time to try to enqueue
2135 std::this_thread::sleep_for(50ms);
2136 EXPECT_FALSE(enqueue_completed); // Should still be blocked
2137
2138 // Release the worker
2139 worker_blocked = false;
2140
2141 // Now it should complete
2142 blocker.join();
2143 pool.wait_all();
2144
2145 EXPECT_TRUE(enqueue_completed);
2146}
2147
2148TEST_F(ThreadPoolTest, EnqueueBoundedThrowsAtHardLimit)
2149{
2150 ThreadPool pool(1);
2151 pool.set_queue_limits(10, 15);
2152
2153 std::atomic<bool> worker_blocked{true};
2154
2155 // Block the worker
2156 pool.enqueue_detached([&worker_blocked] {
2157 while (worker_blocked)
2158 std::this_thread::sleep_for(1ms);
2159 });
2160
2161 // Fill up to hard limit using regular enqueue (bypasses limits)
2162 for (int i = 0; i < 15; ++i)
2163 pool.enqueue_detached([] {});
2164
2165 // Now bounded enqueue should throw
2166 EXPECT_THROW(pool.enqueue_bounded([] { return 0; }), Aleph::queue_overflow_error);
2167
2168 // Clean up
2169 worker_blocked = false;
2170 pool.wait_all();
2171}
2172
2173TEST_F(ThreadPoolTest, QueueOverflowErrorContainsInfo)
2174{
2175 ThreadPool pool(1);
2176 pool.set_queue_limits(5, 10);
2177
2178 std::atomic<bool> worker_blocked{true};
2179 pool.enqueue_detached([&worker_blocked] {
2180 while (worker_blocked)
2181 std::this_thread::sleep_for(1ms);
2182 });
2183
2184 // Fill queue beyond hard limit
2185 for (int i = 0; i < 10; ++i)
2186 pool.enqueue_detached([] {});
2187
2188 try
2189 {
2190 pool.enqueue_bounded([] { return 0; });
2191 FAIL() << "Expected queue_overflow_error";
2192 }
2193 catch (const Aleph::queue_overflow_error& e)
2194 {
2195 EXPECT_GE(e.current_size(), 10u);
2196 EXPECT_EQ(e.hard_limit(), 10u);
2197 EXPECT_NE(std::string(e.what()).find("overflow"), std::string::npos);
2198 }
2199
2200 worker_blocked = false;
2201 pool.wait_all();
2202}
2203
2204TEST_F(ThreadPoolTest, EnqueueBoundedDetachedBlocksAtSoftLimit)
2205{
2206 ThreadPool pool(1);
2207 pool.set_queue_limits(3, 100);
2208
2209 std::atomic<bool> worker_blocked{true};
2210 pool.enqueue_detached([&worker_blocked] {
2211 while (worker_blocked)
2212 std::this_thread::sleep_for(1ms);
2213 });
2214
2215 // Fill to soft limit
2216 for (int i = 0; i < 3; ++i)
2217 pool.enqueue_bounded_detached([] {});
2218
2219 // Next should block
2220 std::atomic<bool> done{false};
2221 std::thread t([&pool, &done] {
2222 pool.enqueue_bounded_detached([] {});
2223 done = true;
2224 });
2225
2226 std::this_thread::sleep_for(30ms);
2227 EXPECT_FALSE(done);
2228
2229 worker_blocked = false;
2230 t.join();
2231 pool.wait_all();
2232
2233 EXPECT_TRUE(done);
2234}
2235
2236TEST_F(ThreadPoolTest, BoundedEnqueueOnStoppedPoolThrows)
2237{
2238 ThreadPool pool(2);
2239 pool.set_queue_limits(100, 1000);
2240 pool.shutdown();
2241
2242 EXPECT_THROW(pool.enqueue_bounded([] { return 0; }), std::runtime_error);
2243 EXPECT_THROW(pool.enqueue_bounded_detached([] {}), std::runtime_error);
2244}
2245
2246TEST_F(ThreadPoolTest, BackpressureSlowsProducer)
2247{
2248 ThreadPool pool(2);
2249 pool.set_queue_limits(10, 100);
2250
2251 std::atomic<int> produced{0};
2252 std::atomic<int> consumed{0};
2253 std::atomic<bool> stop_producing{false};
2254
2255 // Consumer tasks (slow)
2256 auto consume = [&consumed] {
2257 std::this_thread::sleep_for(5ms);
2258 ++consumed;
2259 };
2260
2261 // Producer thread (fast)
2262 std::thread producer([&] {
2263 while (!stop_producing && produced < 50)
2264 {
2265 try
2266 {
2267 pool.enqueue_bounded_detached(consume);
2268 ++produced;
2269 }
2270 catch (const Aleph::queue_overflow_error&)
2271 {
2272 // Hard limit reached, stop
2273 break;
2274 }
2275 }
2276 });
2277
2278 // Let it run for a bit
2279 std::this_thread::sleep_for(200ms);
2280 stop_producing = true;
2281 producer.join();
2282 pool.wait_all();
2283
2284 // Producer should have been slowed down by backpressure
2285 // (can't produce much faster than consumers can consume)
2286 EXPECT_EQ(consumed.load(), produced.load());
2287}
2288
2289TEST_F(ThreadPoolTest, ConcurrentBoundedEnqueue)
2290{
2291 ThreadPool pool(4);
2292 pool.set_queue_limits(50, 200);
2293
2294 std::atomic<int> counter{0};
2295 const int num_producers = 8;
2296 const int tasks_per_producer = 100;
2297
2298 std::vector<std::thread> producers;
2299 for (int p = 0; p < num_producers; ++p)
2300 {
2301 producers.emplace_back([&pool, &counter, tasks_per_producer] {
2302 for (int i = 0; i < tasks_per_producer; ++i)
2303 {
2304 try
2305 {
2307 }
2308 catch (const Aleph::queue_overflow_error&)
2309 {
2310 // Retry after small delay
2311 std::this_thread::sleep_for(1ms);
2312 --i;
2313 }
2314 }
2315 });
2316 }
2317
2318 for (auto& t : producers)
2319 t.join();
2320
2321 pool.wait_all();
2322
2323 EXPECT_EQ(counter.load(), num_producers * tasks_per_producer);
2324}
2325
2326TEST_F(ThreadPoolTest, BoundedEnqueueWithFutureResults)
2327{
2328 ThreadPool pool(4);
2329 pool.set_queue_limits(20, 100);
2330
2331 std::vector<std::future<int>> futures;
2332 for (int i = 0; i < 100; ++i)
2333 futures.push_back(pool.enqueue_bounded([i] { return i * i; }));
2334
2335 for (int i = 0; i < 100; ++i)
2336 EXPECT_EQ(futures[i].get(), i * i);
2337}
2338
2339TEST_F(ThreadPoolTest, BoundedEnqueueExceptionPropagation)
2340{
2341 ThreadPool pool(2);
2342 pool.set_queue_limits(10, 100);
2343
2344 auto future = pool.enqueue_bounded([]() -> int {
2345 throw std::runtime_error("test");
2346 });
2347
2348 EXPECT_THROW(future.get(), std::runtime_error);
2349}
2350
2351TEST_F(ThreadPoolTest, MixedBoundedAndUnboundedEnqueue)
2352{
2353 ThreadPool pool(4);
2354 pool.set_queue_limits(10, 50);
2355
2356 std::atomic<int> counter{0};
2357
2358 // Mix bounded and unbounded
2359 for (int i = 0; i < 100; ++i)
2360 {
2361 if (i % 2 == 0)
2362 pool.enqueue_detached([&counter] { ++counter; });
2363 else
2364 {
2365 try
2366 {
2368 }
2369 catch (const Aleph::queue_overflow_error&)
2370 {
2371 // Unbounded doesn't care about limits
2372 pool.enqueue_detached([&counter] { ++counter; });
2373 }
2374 }
2375 }
2376
2377 pool.wait_all();
2378 EXPECT_EQ(counter.load(), 100);
2379}
2380
2381TEST_F(ThreadPoolTest, BoundedEnqueueStressTest)
2382{
2383 ThreadPool pool(8);
2384 pool.set_queue_limits(100, 500);
2385
2386 std::atomic<int> counter{0};
2387 const int num_tasks = 10000;
2388
2389 for (int i = 0; i < num_tasks; ++i)
2390 {
2391 // Keep trying until successful
2392 bool success = false;
2393 while (!success)
2394 {
2395 try
2396 {
2398 success = true;
2399 }
2400 catch (const Aleph::queue_overflow_error&)
2401 {
2402 std::this_thread::sleep_for(100us);
2403 }
2404 }
2405 }
2406
2407 pool.wait_all();
2408 EXPECT_EQ(counter.load(), num_tasks);
2409}
2410
2411// Note: soft_limit=0 is not a practical use case and has edge case issues,
2412// so we don't test it. Use soft_limit >= 1 for bounded queues.
2413
2414TEST_F(ThreadPoolTest, UnlimitedByDefault)
2415{
2416 ThreadPool pool(2);
2417
2418 auto [soft, hard] = pool.get_queue_limits();
2419
2420 EXPECT_EQ(soft, std::numeric_limits<size_t>::max());
2421 EXPECT_EQ(hard, std::numeric_limits<size_t>::max());
2422}
2423
2424TEST_F(ThreadPoolTest, BoundedEnqueueWithArguments)
2425{
2426 ThreadPool pool(2);
2427 pool.set_queue_limits(10, 100);
2428
2429 auto future = pool.enqueue_bounded([](int a, int b, int c) {
2430 return a + b + c;
2431 }, 10, 20, 12);
2432
2433 EXPECT_EQ(future.get(), 42);
2434}
2435
2436TEST_F(ThreadPoolTest, BoundedEnqueueWithReference)
2437{
2438 ThreadPool pool(2);
2439 pool.set_queue_limits(10, 100);
2440
2441 int value = 10;
2442 auto future = pool.enqueue_bounded([](int& x) { x *= 2; return x; },
2443 std::ref(value));
2444
2445 EXPECT_EQ(future.get(), 20);
2446 EXPECT_EQ(value, 20);
2447}
2448
2449// ============================================================================
2450// Try Enqueue Tests
2451// ============================================================================
2452
2453TEST_F(ThreadPoolTest, TryEnqueueSucceedsWhenSpaceAvailable)
2454{
2455 ThreadPool pool(2);
2456 pool.set_queue_limits(10, 100);
2457
2458 auto result = pool.try_enqueue([] { return 42; });
2459
2460 ASSERT_TRUE(result.has_value());
2461 EXPECT_EQ(result->get(), 42);
2462}
2463
2464TEST_F(ThreadPoolTest, TryEnqueueFailsWhenQueueFull)
2465{
2466 ThreadPool pool(1);
2467 pool.set_queue_limits(5, 100);
2468
2469 std::atomic<bool> worker_blocked{true};
2470 pool.enqueue_detached([&worker_blocked] {
2471 while (worker_blocked)
2472 std::this_thread::sleep_for(1ms);
2473 });
2474
2475 // Fill to soft limit
2476 for (int i = 0; i < 5; ++i)
2477 pool.enqueue_detached([] {});
2478
2479 // try_enqueue should return nullopt
2480 auto result = pool.try_enqueue([] { return 0; });
2481 EXPECT_FALSE(result.has_value());
2482
2483 worker_blocked = false;
2484 pool.wait_all();
2485}
2486
2487TEST_F(ThreadPoolTest, TryEnqueueDetachedSucceeds)
2488{
2489 ThreadPool pool(2);
2490 pool.set_queue_limits(10, 100);
2491 std::atomic<int> counter{0};
2492
2493 bool success = pool.try_enqueue_detached([&counter] { ++counter; });
2494
2495 EXPECT_TRUE(success);
2496 pool.wait_all();
2497 EXPECT_EQ(counter.load(), 1);
2498}
2499
2500TEST_F(ThreadPoolTest, TryEnqueueDetachedFailsWhenFull)
2501{
2502 ThreadPool pool(1);
2503 pool.set_queue_limits(3, 100);
2504
2505 std::atomic<bool> worker_blocked{true};
2506 pool.enqueue_detached([&worker_blocked] {
2507 while (worker_blocked)
2508 std::this_thread::sleep_for(1ms);
2509 });
2510
2511 // Fill to soft limit
2512 for (int i = 0; i < 3; ++i)
2513 pool.enqueue_detached([] {});
2514
2515 // try_enqueue_detached should return false
2516 bool success = pool.try_enqueue_detached([] {});
2517 EXPECT_FALSE(success);
2518
2519 worker_blocked = false;
2520 pool.wait_all();
2521}
2522
2523TEST_F(ThreadPoolTest, TryEnqueueOnStoppedPoolThrows)
2524{
2525 ThreadPool pool(2);
2526 pool.shutdown();
2527
2528 EXPECT_THROW(pool.try_enqueue([] { return 0; }), std::runtime_error);
2529 EXPECT_THROW(pool.try_enqueue_detached([] {}), std::runtime_error);
2530}
2531
2532TEST_F(ThreadPoolTest, TryEnqueueWithArguments)
2533{
2534 ThreadPool pool(2);
2535 pool.set_queue_limits(10, 100);
2536
2537 auto result = pool.try_enqueue([](int a, int b) { return a + b; }, 20, 22);
2538
2539 ASSERT_TRUE(result.has_value());
2540 EXPECT_EQ(result->get(), 42);
2541}
2542
2543TEST_F(ThreadPoolTest, TryEnqueueNonBlockingBehavior)
2544{
2545 ThreadPool pool(1);
2546 pool.set_queue_limits(2, 100);
2547
2548 std::atomic<bool> worker_blocked{true};
2549 pool.enqueue_detached([&worker_blocked] {
2550 while (worker_blocked)
2551 std::this_thread::sleep_for(1ms);
2552 });
2553
2554 // Fill queue
2555 pool.enqueue_detached([] {});
2556 pool.enqueue_detached([] {});
2557
2558 // With the queue full, each call says so at once instead of waiting for
2559 // room. Without a clock: the worker stays blocked until after the loop, so
2560 // that a call that waited would never end the test
2561 int refused = 0;
2562 for (int i = 0; i < 1000; ++i)
2563 if (not pool.try_enqueue([] { return 0; }).has_value())
2564 ++refused;
2565 EXPECT_EQ(refused, 1000);
2566
2567 worker_blocked = false;
2568 pool.wait_all();
2569}
2570
2571// ============================================================================
2572// Benchmark Tests
2573// ============================================================================
2574
2575// The CPUs that this process may use: hardware_concurrency() counts those of
2576// the machine, also when a cpuset (a container, a CI runner) allows fewer
2577static size_t usable_cpus()
2578{
2579#if defined(__linux__) && defined(CPU_COUNT)
2580 cpu_set_t set;
2581 if (sched_getaffinity(0, sizeof(set), &set) == 0)
2582 return static_cast<size_t>(CPU_COUNT(&set));
2583#endif
2584 return std::max(1u, std::thread::hardware_concurrency());
2585}
2586
2587TEST_F(ThreadPoolTest, BenchmarkVsSequential)
2588{
2589 const int num_tasks = 1000;
2590 const auto work_duration = 100us;
2591
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)
2595 ; // Busy wait
2596 return 1;
2597 };
2598
2599 // Sequential baseline
2600 auto seq_start = std::chrono::high_resolution_clock::now();
2601 int seq_sum = 0;
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);
2606
2607 // As many threads as CPUs this process may use, at most 8: more threads
2608 // than CPUs would measure the scheduler of the machine, not the pool
2609 size_t num_threads = std::min<size_t>(usable_cpus(), 8);
2610 ThreadPool pool(num_threads);
2611
2612 // The best of three tries, so that what it prints is the time of the pool
2613 // rather than that of a busy machine. It asserts no speedup: on a machine
2614 // whose cores are all busy no pool goes faster than one thread, and the
2615 // test failed so on the runners of the CI. That the pool runs its tasks at
2616 // once is what RunsAsManyTasksAtOnceAsItHasThreads checks, without a clock
2617 int pool_sum = 0;
2618 auto pool_duration = std::chrono::milliseconds::max();
2619 for (int attempt = 0; attempt < 3; ++attempt)
2620 {
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));
2626
2627 pool_sum = 0;
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));
2633 }
2634
2635 EXPECT_EQ(seq_sum, pool_sum);
2636
2637 double speedup = static_cast<double>(seq_duration.count()) / pool_duration.count();
2638
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";
2646}
2647
2648TEST_F(ThreadPoolTest, BenchmarkEnqueueOverhead)
2649{
2650 ThreadPool pool(4);
2651 const int num_tasks = 100000;
2652
2653 // Measure enqueue overhead (tasks do nothing)
2654 auto start = std::chrono::high_resolution_clock::now();
2655 for (int i = 0; i < num_tasks; ++i)
2656 pool.enqueue_detached([] {});
2657 pool.wait_all();
2658 auto end = std::chrono::high_resolution_clock::now();
2659
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;
2662
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";
2670
2671 // Should be able to enqueue at least 50k tasks/sec
2672 // (relaxed for slower CI environments)
2673 EXPECT_LT(ns_per_task, 25000); // < 25μs per task
2674}
2675
2676TEST_F(ThreadPoolTest, BenchmarkVsStdAsync)
2677{
2678 const int num_tasks = 500; // Fewer tasks because async is slow
2679
2680 auto compute = [](int x) -> long long {
2681 long long sum = 0;
2682 for (int i = 0; i < 1000; ++i)
2683 sum += static_cast<long long>(i) * x;
2684 return sum;
2685 };
2686
2687 // std::async makes a thread for each task. They are made in batches of as
2688 // many as the pool has threads, each one waited for before the next, so
2689 // that the test does not make 500 threads at once, as it did when it
2690 // ended once with a segmentation fault on a runner of the CI
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)
2698 {
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();
2705 }
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);
2708
2709 // ThreadPool, with as many threads as a batch of std::async
2710 ThreadPool pool(num_threads);
2711
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));
2717
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);
2723
2724 EXPECT_EQ(async_sum, pool_sum);
2725
2726 double speedup = static_cast<double>(async_duration.count()) / pool_duration.count();
2727
2728 // As BenchmarkVsSequential, it prints the times and asserts no speedup:
2729 // on a busy machine they are not those of the pool
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";
2736}
2737
2738// =============================================================================
2739// New Features Tests
2740// =============================================================================
2741
2742// --- Statistics Tests ---
2743
2744TEST_F(ThreadPoolTest, GetStatsInitialValues)
2745{
2746 ThreadPool pool(2);
2747 auto stats = pool.get_stats();
2748
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);
2756}
2757
2758TEST_F(ThreadPoolTest, StatsTrackCompletedTasks)
2759{
2760 ThreadPool pool(2);
2761
2762 std::vector<std::future<int>> futures;
2763 for (int i = 0; i < 10; ++i)
2764 futures.push_back(pool.enqueue([] { return 42; }));
2765
2766 for (auto& f : futures)
2767 f.get();
2768
2769 pool.wait_all();
2770
2771 auto stats = pool.get_stats();
2772 EXPECT_EQ(stats.tasks_completed, 10u);
2773 EXPECT_EQ(stats.total_processed(), 10u);
2774}
2775
2776TEST_F(ThreadPoolTest, StatsTrackPeakQueueSize)
2777{
2778 ThreadPool pool(1);
2779
2780 // Block the worker
2781 std::promise<void> blocker;
2782 pool.enqueue([&blocker] { blocker.get_future().wait(); });
2783
2784 // Queue up several tasks
2785 for (int i = 0; i < 5; ++i)
2786 pool.enqueue_detached([] {});
2787
2788 std::this_thread::sleep_for(std::chrono::milliseconds(10));
2789
2790 auto stats = pool.get_stats();
2791 EXPECT_GE(stats.peak_queue_size, 5u);
2792
2793 // Release worker
2794 blocker.set_value();
2795 pool.wait_all();
2796}
2797
2798TEST_F(ThreadPoolTest, ResetStatsWorks)
2799{
2800 ThreadPool pool(2);
2801
2802 pool.enqueue([] { return 1; }).get();
2803 // Wait for stats to be updated (tasks_completed incremented after future is set)
2804 pool.wait_all();
2805
2806 auto stats1 = pool.get_stats();
2807 EXPECT_GE(stats1.tasks_completed, 1u);
2808
2809 pool.reset_stats();
2810
2811 auto stats2 = pool.get_stats();
2812 EXPECT_EQ(stats2.tasks_completed, 0u);
2813 EXPECT_EQ(stats2.peak_queue_size, 0u);
2814}
2815
2816// --- Exception Callback Tests ---
2817
2818TEST_F(ThreadPoolTest, ExceptionCallbackInvokedOnDetachedTaskFailure)
2819{
2820 ThreadPool pool(2);
2821
2822 std::atomic<bool> callback_called{false};
2823 std::atomic<bool> correct_exception{false};
2824
2825 pool.set_exception_callback([&](std::exception_ptr ep) {
2826 callback_called = true;
2827 try {
2828 std::rethrow_exception(ep);
2829 } catch (const std::runtime_error& e) {
2830 correct_exception = (std::string(e.what()) == "test error");
2831 } catch (...) {
2832 correct_exception = false;
2833 }
2834 });
2835
2836 pool.enqueue_detached([] {
2837 throw std::runtime_error("test error");
2838 });
2839
2840 pool.wait_all();
2841 std::this_thread::sleep_for(std::chrono::milliseconds(50));
2842
2843 EXPECT_TRUE(callback_called.load());
2844 EXPECT_TRUE(correct_exception.load());
2845}
2846
2847TEST_F(ThreadPoolTest, ExceptionCallbackCanBeCleared)
2848{
2849 ThreadPool pool(2);
2850
2851 std::atomic<int> callback_count{0};
2852
2853 pool.set_exception_callback([&](std::exception_ptr) {
2854 ++callback_count;
2855 });
2856
2857 pool.enqueue_detached([] { throw std::runtime_error("error"); });
2858 pool.wait_all();
2859 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2860
2861 EXPECT_EQ(callback_count.load(), 1);
2862
2863 // Clear callback
2864 pool.set_exception_callback(nullptr);
2865
2866 pool.enqueue_detached([] { throw std::runtime_error("error"); });
2867 pool.wait_all();
2868 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2869
2870 // Count should still be 1
2871 EXPECT_EQ(callback_count.load(), 1);
2872}
2873
2874TEST_F(ThreadPoolTest, StatsTrackFailedDetachedTasks)
2875{
2876 ThreadPool pool(2);
2877
2878 pool.enqueue_detached([] { throw std::runtime_error("fail"); });
2879 pool.enqueue_detached([] { throw std::logic_error("fail"); });
2880 pool.enqueue_detached([] { /* success */ });
2881
2882 pool.wait_all();
2883 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2884
2885 auto stats = pool.get_stats();
2886 EXPECT_EQ(stats.tasks_failed, 2u);
2887 EXPECT_EQ(stats.tasks_completed, 1u);
2888 EXPECT_EQ(stats.total_processed(), 3u);
2889}
2890
2891// --- wait_all_for/wait_all_until Tests ---
2892
2893TEST_F(ThreadPoolTest, WaitAllForSucceedsWhenIdle)
2894{
2895 ThreadPool pool(2);
2896
2897 pool.enqueue([] { return 42; }).get();
2898
2899 bool result = pool.wait_all_for(std::chrono::milliseconds(100));
2900 EXPECT_TRUE(result);
2901}
2902
2903TEST_F(ThreadPoolTest, WaitAllForTimesOutWhenBusy)
2904{
2905 ThreadPool pool(1);
2906
2907 // Start a long task
2908 pool.enqueue_detached([] {
2909 std::this_thread::sleep_for(std::chrono::milliseconds(500));
2910 });
2911
2912 std::this_thread::sleep_for(std::chrono::milliseconds(10));
2913
2914 bool result = pool.wait_all_for(std::chrono::milliseconds(50));
2915 EXPECT_FALSE(result);
2916
2917 // Wait for cleanup
2918 pool.wait_all();
2919}
2920
2921TEST_F(ThreadPoolTest, WaitAllUntilWorks)
2922{
2923 ThreadPool pool(2);
2924
2925 pool.enqueue([] { return 1; }).get();
2926
2927 auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(100);
2928 bool result = pool.wait_all_until(deadline);
2929 EXPECT_TRUE(result);
2930}
2931
2932// --- enqueue_batch Tests ---
2933
2934TEST_F(ThreadPoolTest, EnqueueBatchExecutesAllTasks)
2935{
2936 ThreadPool pool(4);
2937
2938 std::vector<std::tuple<int, int>> args = {
2939 {1, 2}, {3, 4}, {5, 6}, {7, 8}
2940 };
2941
2942 auto futures = pool.enqueue_batch([](int a, int b) { return a + b; }, args);
2943
2944 EXPECT_EQ(futures.size(), 4u);
2945
2946 std::vector<int> results;
2947 for (auto& f : futures)
2948 results.push_back(f.get());
2949
2950 EXPECT_EQ(results, (std::vector<int>{3, 7, 11, 15}));
2951}
2952
2953TEST_F(ThreadPoolTest, EnqueueBatchWithLargeWorkload)
2954{
2955 ThreadPool pool(4);
2956
2957 std::vector<std::tuple<int>> args;
2958 for (int i = 0; i < 100; ++i)
2959 args.emplace_back(i);
2960
2961 auto futures = pool.enqueue_batch([](int x) { return x * x; }, args);
2962
2963 int sum = 0;
2964 for (auto& f : futures)
2965 sum += f.get();
2966
2967 // Sum of squares 0^2 + 1^2 + ... + 99^2 = 328350
2968 EXPECT_EQ(sum, 328350);
2969}
2970
2971TEST_F(ThreadPoolTest, EnqueueBatchEmptyContainer)
2972{
2973 ThreadPool pool(2);
2974
2975 std::vector<std::tuple<int>> empty;
2976 auto futures = pool.enqueue_batch([](int x) { return x; }, empty);
2977
2978 EXPECT_TRUE(futures.empty());
2979}
2980
2981// --- parallel_for Tests ---
2982
2983TEST_F(ThreadPoolTest, ParallelForModifiesElements)
2984{
2985 ThreadPool pool(4);
2986
2987 std::vector<int> data(100, 1);
2988
2989 parallel_for(pool, data.begin(), data.end(), [](int& x) { x *= 2; });
2990
2991 for (int x : data)
2992 EXPECT_EQ(x, 2);
2993}
2994
2995TEST_F(ThreadPoolTest, ParallelForWithChunkFunction)
2996{
2997 ThreadPool pool(4);
2998
2999 std::vector<int> data(100, 1);
3000
3001 parallel_for(pool, data.begin(), data.end(),
3002 [](auto begin, auto end) {
3003 for (auto it = begin; it != end; ++it)
3004 *it = 5;
3005 });
3006
3007 for (int x : data)
3008 EXPECT_EQ(x, 5);
3009}
3010
3011TEST_F(ThreadPoolTest, ParallelForEmptyRange)
3012{
3013 ThreadPool pool(2);
3014
3015 std::vector<int> empty;
3016
3017 // Should not throw or crash
3018 parallel_for(pool, empty.begin(), empty.end(), [](int& x) { x = 0; });
3019
3020 EXPECT_TRUE(empty.empty());
3021}
3022
3023TEST_F(ThreadPoolTest, ParallelForCustomChunkSize)
3024{
3025 ThreadPool pool(2);
3026
3027 std::vector<std::atomic<int>> data(50);
3028 for (auto& x : data)
3029 x = 0;
3030
3031 parallel_for(pool, data.begin(), data.end(),
3032 [](std::atomic<int>& x) { ++x; },
3033 10); // chunk size = 10
3034
3035 for (const auto& x : data)
3036 EXPECT_EQ(x.load(), 1);
3037}
3038
3039// --- parallel_for_index Tests ---
3040
3041TEST_F(ThreadPoolTest, ParallelForIndexWorks)
3042{
3043 ThreadPool pool(4);
3044
3045 std::vector<int> data(100, 0);
3046
3047 parallel_for_index(pool, 0, data.size(), [&data](size_t i) {
3048 data[i] = static_cast<int>(i * 2);
3049 });
3050
3051 for (size_t i = 0; i < data.size(); ++i)
3052 EXPECT_EQ(data[i], static_cast<int>(i * 2));
3053}
3054
3055TEST_F(ThreadPoolTest, ParallelForIndexEmptyRange)
3056{
3057 ThreadPool pool(2);
3058
3059 // Should not throw
3060 parallel_for_index(pool, 10, 10, [](size_t) { /* nothing */ });
3061 parallel_for_index(pool, 10, 5, [](size_t) { /* nothing */ });
3062}
3063
3064// --- parallel_transform Tests ---
3065
3066TEST_F(ThreadPoolTest, ParallelTransformBasic)
3067{
3068 ThreadPool pool(4);
3069
3070 std::vector<int> input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
3071 std::vector<int> output(10);
3072
3073 parallel_transform(pool, input.begin(), input.end(), output.begin(),
3074 [](int x) { return x * x; });
3075
3076 EXPECT_EQ(output, (std::vector<int>{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}));
3077}
3078
3079TEST_F(ThreadPoolTest, ParallelTransformLargeData)
3080{
3081 ThreadPool pool(4);
3082
3083 std::vector<int> input(1000);
3084 std::iota(input.begin(), input.end(), 0);
3085
3086 std::vector<int> output(1000);
3087
3088 parallel_transform(pool, input.begin(), input.end(), output.begin(),
3089 [](int x) { return x + 1; });
3090
3091 for (int i = 0; i < 1000; ++i)
3092 EXPECT_EQ(output[i], i + 1);
3093}
3094
3095TEST_F(ThreadPoolTest, ParallelTransformEmpty)
3096{
3097 ThreadPool pool(2);
3098
3099 std::vector<int> input;
3100 std::vector<int> output;
3101
3102 auto end = parallel_transform(pool, input.begin(), input.end(),
3103 output.begin(), [](int x) { return x; });
3104
3105 EXPECT_EQ(end, output.begin());
3106}
3107
3108// --- parallel_reduce Tests ---
3109
3110TEST_F(ThreadPoolTest, ParallelReduceSum)
3111{
3112 ThreadPool pool(4);
3113
3114 std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
3115
3116 int sum = parallel_reduce(pool, data.begin(), data.end(), 0, std::plus<int>());
3117
3118 EXPECT_EQ(sum, 55);
3119}
3120
3121TEST_F(ThreadPoolTest, ParallelReduceProduct)
3122{
3123 ThreadPool pool(4);
3124
3125 std::vector<int> data = {1, 2, 3, 4, 5};
3126
3127 int product = parallel_reduce(pool, data.begin(), data.end(), 1,
3128 std::multiplies<int>());
3129
3130 EXPECT_EQ(product, 120);
3131}
3132
3133TEST_F(ThreadPoolTest, ParallelReduceMax)
3134{
3135 ThreadPool pool(4);
3136
3137 std::vector<int> data = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
3138
3139 int max_val = parallel_reduce(pool, data.begin(), data.end(),
3140 std::numeric_limits<int>::min(),
3141 [](int a, int b) { return std::max(a, b); });
3142
3143 EXPECT_EQ(max_val, 9);
3144}
3145
3146TEST_F(ThreadPoolTest, ParallelReduceLargeData)
3147{
3148 ThreadPool pool(4);
3149
3150 std::vector<long long> data(10000);
3151 std::iota(data.begin(), data.end(), 1LL);
3152
3153 long long sum = parallel_reduce(pool, data.begin(), data.end(), 0LL,
3154 std::plus<long long>());
3155
3156 // Sum 1+2+...+10000 = 10000*10001/2 = 50005000
3157 EXPECT_EQ(sum, 50005000LL);
3158}
3159
3160TEST_F(ThreadPoolTest, ParallelReduceEmpty)
3161{
3162 ThreadPool pool(2);
3163
3164 std::vector<int> empty;
3165
3166 int result = parallel_reduce(pool, empty.begin(), empty.end(), 42,
3167 std::plus<int>());
3168
3169 EXPECT_EQ(result, 42); // Returns init for empty range
3170}
3171
3172// --- ThreadPoolStats Tests ---
3173
3174TEST_F(ThreadPoolTest, ThreadPoolStatsQueueUtilization)
3175{
3176 ThreadPoolStats stats;
3177 stats.current_queue_size = 50;
3178
3179 EXPECT_NEAR(stats.queue_utilization(100), 50.0, 0.01);
3180 EXPECT_NEAR(stats.queue_utilization(200), 25.0, 0.01);
3181 EXPECT_NEAR(stats.queue_utilization(0), 0.0, 0.01); // Edge case
3182 EXPECT_NEAR(stats.queue_utilization(std::numeric_limits<size_t>::max()), 0.0, 0.01);
3183}
3184
3185int main(int argc, char **argv)
3186{
3187 ::testing::InitGoogleTest(&argc, argv);
3188 return RUN_ALL_TESTS();
3189}
int main()
long double h
Definition btreepic.C:154
size_t size_t int32_t value
Definition ca-c-api.h:116
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.
void SetUp() override
void TearDown() override
#define FAIL(msg)
static mpfr_t y
Definition mpfr_mul_d.c:3
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.
Definition ah-zip.H:183
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[]
Definition ntreepic.C:1890
#define LL
Definition ran_array.c:24
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.
static int square(int x)
int multiply(int a, int b) const
int operator()(int x) const
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static long counter
Definition test-splice.C:40
A modern, efficient thread pool for parallel task execution.
int free_function(int x)
void increment_ref(int &x)
TEST_F(ThreadPoolTest, DefaultConstruction)
static size_t usable_cpus()
void add_to_ref(int &x, int amount)
ofstream output
Definition writeHeap.C:215