Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ah_parallel_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
37#include <gtest/gtest.h>
38#include <climits>
39#include <cstdlib>
40#include <ah-parallel.H>
41#include <vector>
42#include <list>
43#include <deque>
44#include <array>
45#include <string>
46#include <numeric>
47#include <atomic>
48#include <chrono>
49#include <random>
50#include <algorithm>
51#include <cmath>
52
53using namespace Aleph;
54
55// =============================================================================
56// Test Fixture
57// =============================================================================
58
59class ParallelTest : public ::testing::Test
60{
61protected:
63
64 std::vector<int> empty_vec;
65 std::vector<int> single_vec = {42};
66 std::vector<int> small_vec = {1, 2, 3, 4, 5};
67 std::vector<int> large_vec;
68
69 void SetUp() override
70 {
71 large_vec.resize(10000);
72 std::iota(large_vec.begin(), large_vec.end(), 1);
73 }
74};
75
76// =============================================================================
77// pmaps Tests
78// =============================================================================
79
80TEST_F(ParallelTest, PmapsSquare)
81{
82 auto result = pmaps(pool, small_vec, [](int x) { return x * x; });
83 ASSERT_EQ(result.size(), 5u);
84 EXPECT_EQ(result, (std::vector<int>{1, 4, 9, 16, 25}));
85}
86
87TEST_F(ParallelTest, PmapsTypeConversion)
88{
89 auto result = pmaps<double>(pool, small_vec, [](int x) { return x * 1.5; });
90 ASSERT_EQ(result.size(), 5u);
91 EXPECT_NEAR(result[0], 1.5, 0.001);
92 EXPECT_NEAR(result[4], 7.5, 0.001);
93}
94
95TEST_F(ParallelTest, PmapsToString)
96{
97 auto result = pmaps(pool, small_vec, [](int x) { return std::to_string(x); });
98 ASSERT_EQ(result.size(), 5u);
99 EXPECT_EQ(result[0], "1");
100 EXPECT_EQ(result[4], "5");
101}
102
104{
105 auto result = pmaps(pool, empty_vec, [](int x) { return x * 2; });
106 EXPECT_TRUE(result.empty());
107}
108
109TEST_F(ParallelTest, PmapsSingle)
110{
111 auto result = pmaps(pool, single_vec, [](int x) { return x * 2; });
112 ASSERT_EQ(result.size(), 1u);
113 EXPECT_EQ(result[0], 84);
114}
115
116TEST_F(ParallelTest, PmapsLargeData)
117{
118 auto result = pmaps(pool, large_vec, [](int x) { return x * 2; });
119 ASSERT_EQ(result.size(), 10000u);
120 for (size_t i = 0; i < result.size(); ++i)
121 EXPECT_EQ(result[i], static_cast<int>((i + 1) * 2));
122}
123
124TEST_F(ParallelTest, PmapsWithList)
125{
126 std::list<int> lst = {1, 2, 3, 4, 5};
127 auto result = pmaps(pool, lst, [](int x) { return x * x; });
128 EXPECT_EQ(result, (std::vector<int>{1, 4, 9, 16, 25}));
129}
130
131TEST_F(ParallelTest, PmapsPreservesOrder)
132{
133 auto result = pmaps(pool, large_vec, [](int x) { return x; });
134 for (size_t i = 0; i < result.size(); ++i)
135 EXPECT_EQ(result[i], static_cast<int>(i + 1));
136}
137
138TEST_F(ParallelTest, PmapsAcceptsParallelOptions)
139{
141 options.pool = &pool;
142 options.min_size = large_vec.size() + 1;
143 options.chunk_size = 7;
144 options.max_tasks = 2;
145
146 auto result = pmaps(large_vec, [](int x) { return x + 1; }, options);
147 ASSERT_EQ(result.size(), large_vec.size());
148 EXPECT_EQ(result.front(), 2);
149 EXPECT_EQ(result.back(), 10001);
150}
151
152// =============================================================================
153// pfilter Tests
154// =============================================================================
155
156TEST_F(ParallelTest, PfilterEvens)
157{
158 auto result = pfilter(pool, small_vec, [](int x) { return x % 2 == 0; });
159 EXPECT_EQ(result, (std::vector<int>{2, 4}));
160}
161
162TEST_F(ParallelTest, PfilterOdds)
163{
164 auto result = pfilter(pool, small_vec, [](int x) { return x % 2 != 0; });
165 EXPECT_EQ(result, (std::vector<int>{1, 3, 5}));
166}
167
168TEST_F(ParallelTest, PfilterNone)
169{
170 auto result = pfilter(pool, small_vec, [](int x) { return x > 100; });
171 EXPECT_TRUE(result.empty());
172}
173
175{
176 auto result = pfilter(pool, small_vec, [](int x) { return x > 0; });
177 EXPECT_EQ(result.size(), 5u);
178}
179
180TEST_F(ParallelTest, PfilterEmpty)
181{
182 auto result = pfilter(pool, empty_vec, [](int) { return true; });
183 EXPECT_TRUE(result.empty());
184}
185
186TEST_F(ParallelTest, PfilterPreservesOrder)
187{
188 std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
189 auto result = pfilter(pool, nums, [](int x) { return x % 3 == 0; });
190 EXPECT_EQ(result, (std::vector<int>{3, 6, 9}));
191}
192
193TEST_F(ParallelTest, PfilterLargeData)
194{
195 auto result = pfilter(pool, large_vec, [](int x) { return x % 100 == 0; });
196 EXPECT_EQ(result.size(), 100u);
197 EXPECT_EQ(result[0], 100);
198 EXPECT_EQ(result[99], 10000);
199}
200
201TEST_F(ParallelTest, ParallelAlgorithmsHonorCancellation)
202{
203 CancellationSource source;
205 options.pool = &pool;
206 options.chunk_size = 32;
207 options.cancel_token = source.token();
208
209 EXPECT_THROW(pmaps(large_vec,
210 [&source](int x) {
211 if (x == 128)
212 source.request_cancel();
213 return x * 2;
214 },
215 options),
217}
218
219// =============================================================================
220// pfoldl Tests
221// =============================================================================
222
224{
225 int sum = pfoldl(pool, small_vec, 0, std::plus<int>());
226 EXPECT_EQ(sum, 15);
227}
228
229TEST_F(ParallelTest, PfoldlProduct)
230{
231 int product = pfoldl(pool, small_vec, 1, std::multiplies<int>());
232 EXPECT_EQ(product, 120);
233}
234
236{
237 int max_val = pfoldl(pool, small_vec, INT_MIN,
238 [](int a, int b) { return std::max(a, b); });
239 EXPECT_EQ(max_val, 5);
240}
241
242TEST_F(ParallelTest, PfoldlEmpty)
243{
244 int result = pfoldl(pool, empty_vec, 42, std::plus<int>());
245 EXPECT_EQ(result, 42);
246}
247
248TEST_F(ParallelTest, PfoldlLargeData)
249{
250 long long sum = pfoldl(pool, large_vec, 0LL,
251 [](long long a, int b) { return a + b; });
252 // Sum 1..10000 = 10000*10001/2 = 50005000
253 EXPECT_EQ(sum, 50005000LL);
254}
255
256// =============================================================================
257// pfor_each Tests
258// =============================================================================
259
260TEST_F(ParallelTest, PforEachModify)
261{
262 std::vector<int> data = {1, 2, 3, 4, 5};
263 pfor_each(pool, data, [](int& x) { x *= 2; });
264 EXPECT_EQ(data, (std::vector<int>{2, 4, 6, 8, 10}));
265}
266
267TEST_F(ParallelTest, PforEachAtomic)
268{
269 std::atomic<int> count{0};
270 pfor_each(pool, large_vec, [&count](const int& x) {
271 if (x % 2 == 0) ++count;
272 });
273 EXPECT_EQ(count.load(), 5000);
274}
275
276TEST_F(ParallelTest, PforEachEmpty)
277{
278 std::atomic<int> count{0};
279 pfor_each(pool, empty_vec, [&count](int) { ++count; });
280 EXPECT_EQ(count.load(), 0);
281}
282
283TEST_F(ParallelTest, PforEachAcceptsDefaultPoolThroughOptions)
284{
285 std::vector<int> data = {1, 2, 3, 4};
288 options.max_tasks = 2;
289
290 pfor_each(data, [](int & x) { x += 5; }, options);
291 EXPECT_EQ(data, (std::vector<int>{6, 7, 8, 9}));
292}
293
294// =============================================================================
295// pall, pexists, pnone Tests
296// =============================================================================
297
299{
300 bool result = pall(pool, small_vec, [](int x) { return x > 0; });
301 EXPECT_TRUE(result);
302}
303
305{
306 bool result = pall(pool, small_vec, [](int x) { return x > 3; });
307 EXPECT_FALSE(result);
308}
309
311{
312 bool result = pall(pool, empty_vec, [](int) { return false; });
313 EXPECT_TRUE(result); // Vacuous truth
314}
315
316TEST_F(ParallelTest, PexistsTrue)
317{
318 bool result = pexists(pool, small_vec, [](int x) { return x == 3; });
319 EXPECT_TRUE(result);
320}
321
322TEST_F(ParallelTest, PexistsFalse)
323{
324 bool result = pexists(pool, small_vec, [](int x) { return x > 100; });
325 EXPECT_FALSE(result);
326}
327
328TEST_F(ParallelTest, PexistsEmpty)
329{
330 bool result = pexists(pool, empty_vec, [](int) { return true; });
331 EXPECT_FALSE(result);
332}
333
335{
336 bool result = pnone(pool, small_vec, [](int x) { return x < 0; });
337 EXPECT_TRUE(result);
338}
339
341{
342 bool result = pnone(pool, small_vec, [](int x) { return x == 3; });
343 EXPECT_FALSE(result);
344}
345
346// =============================================================================
347// pcount_if Tests
348// =============================================================================
349
350TEST_F(ParallelTest, PcountIfEvens)
351{
352 size_t count = pcount_if(pool, small_vec, [](int x) { return x % 2 == 0; });
353 EXPECT_EQ(count, 2u);
354}
355
356TEST_F(ParallelTest, PcountIfDivisibleByHundred)
357{
358 size_t count = pcount_if(pool, large_vec, [](int x) { return x % 100 == 0; });
359 EXPECT_EQ(count, 100u);
360}
361
362TEST_F(ParallelTest, PcountIfAll)
363{
364 size_t count = pcount_if(pool, small_vec, [](int x) { return x > 0; });
365 EXPECT_EQ(count, 5u);
366}
367
368TEST_F(ParallelTest, PcountIfNone)
369{
370 size_t count = pcount_if(pool, small_vec, [](int x) { return x > 100; });
371 EXPECT_EQ(count, 0u);
372}
373
374TEST_F(ParallelTest, PcountIfLargeData)
375{
376 size_t count = pcount_if(pool, large_vec, [](int x) { return x % 7 == 0; });
377 EXPECT_EQ(count, 1428u); // floor(10000/7) = 1428
378}
379
380// =============================================================================
381// pfind Tests
382// =============================================================================
383
385{
386 auto idx = pfind(pool, small_vec, [](int x) { return x == 3; });
387 ASSERT_TRUE(idx.has_value());
388 EXPECT_EQ(*idx, 2u);
389}
390
391TEST_F(ParallelTest, PfindNotFound)
392{
393 auto idx = pfind(pool, small_vec, [](int x) { return x == 100; });
394 EXPECT_FALSE(idx.has_value());
395}
396
398{
399 std::vector<int> data = {1, 2, 3, 3, 3, 4, 5};
400 auto idx = pfind(pool, data, [](int x) { return x == 3; });
401 ASSERT_TRUE(idx.has_value());
402 EXPECT_EQ(*idx, 2u); // First occurrence
403}
404
406{
407 auto idx = pfind(pool, empty_vec, [](int) { return true; });
408 EXPECT_FALSE(idx.has_value());
409}
410
411TEST_F(ParallelTest, PfindAcceptsParallelOptions)
412{
414 options.pool = &pool;
415 options.chunk_size = 64;
416 options.max_tasks = 4;
417
418 auto idx = pfind(large_vec, [](int x) { return x == 7777; }, options);
419 ASSERT_TRUE(idx.has_value());
420 EXPECT_EQ(*idx, 7776u);
421}
422
423TEST_F(ParallelTest, PfindValueFound)
424{
425 std::vector<std::string> words = {"apple", "banana", "cherry"};
426 auto found = pfind_value(pool, words,
427 [](const std::string& s) { return s.length() > 5; });
428 ASSERT_TRUE(found.has_value());
429 EXPECT_EQ(*found, "banana");
430}
431
432// =============================================================================
433// psum, pproduct Tests
434// =============================================================================
435
437{
438 auto sum = psum(pool, small_vec);
439 EXPECT_EQ(sum, 15);
440}
441
442TEST_F(ParallelTest, PsumWithInit)
443{
444 auto sum = psum(pool, small_vec, 100);
445 EXPECT_EQ(sum, 115);
446}
447
449{
450 auto sum = psum(pool, empty_vec);
451 EXPECT_EQ(sum, 0);
452}
453
454TEST_F(ParallelTest, PsumLargeData)
455{
456 auto sum = psum<std::vector<int>, long long>(pool, large_vec, 0LL);
457 EXPECT_EQ(sum, 50005000LL);
458}
459
461{
462 auto product = pproduct(pool, small_vec);
463 EXPECT_EQ(product, 120);
464}
465
466TEST_F(ParallelTest, PproductEmpty)
467{
468 auto product = pproduct(pool, empty_vec);
469 EXPECT_EQ(product, 1); // Identity for multiplication
470}
471
472// =============================================================================
473// pmin, pmax, pminmax Tests
474// =============================================================================
475
477{
478 auto min_val = pmin(pool, small_vec);
479 ASSERT_TRUE(min_val.has_value());
480 EXPECT_EQ(*min_val, 1);
481}
482
484{
485 auto max_val = pmax(pool, small_vec);
486 ASSERT_TRUE(max_val.has_value());
487 EXPECT_EQ(*max_val, 5);
488}
489
491{
492 auto min_val = pmin(pool, empty_vec);
493 EXPECT_FALSE(min_val.has_value());
494}
495
497{
498 auto max_val = pmax(pool, empty_vec);
499 EXPECT_FALSE(max_val.has_value());
500}
501
503{
504 auto result = pminmax(pool, small_vec);
505 ASSERT_TRUE(result.has_value());
506 EXPECT_EQ(result->first, 1);
507 EXPECT_EQ(result->second, 5);
508}
509
510TEST_F(ParallelTest, PminmaxShuffle)
511{
512 std::vector<int> data = {5, 1, 3, 2, 4};
513 auto result = pminmax(pool, data);
514 ASSERT_TRUE(result.has_value());
515 EXPECT_EQ(result->first, 1);
516 EXPECT_EQ(result->second, 5);
517}
518
519TEST_F(ParallelTest, PminmaxLargeData)
520{
521 auto result = pminmax(pool, large_vec);
522 ASSERT_TRUE(result.has_value());
523 EXPECT_EQ(result->first, 1);
524 EXPECT_EQ(result->second, 10000);
525}
526
527// =============================================================================
528// psort Tests
529// =============================================================================
530
532{
533 std::vector<int> data = {5, 2, 8, 1, 9, 3, 7, 4, 6};
534 psort(pool, data);
535 EXPECT_EQ(data, (std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9}));
536}
537
538TEST_F(ParallelTest, PsortDescending)
539{
540 std::vector<int> data = {5, 2, 8, 1, 9, 3, 7, 4, 6};
541 psort(pool, data, std::greater<int>());
542 EXPECT_EQ(data, (std::vector<int>{9, 8, 7, 6, 5, 4, 3, 2, 1}));
543}
544
546{
547 std::vector<int> data;
548 psort(pool, data);
549 EXPECT_TRUE(data.empty());
550}
551
552TEST_F(ParallelTest, PsortSingle)
553{
554 std::vector<int> data = {42};
555 psort(pool, data);
556 EXPECT_EQ(data[0], 42);
557}
558
559TEST_F(ParallelTest, PsortAlreadySorted)
560{
561 std::vector<int> data = {1, 2, 3, 4, 5};
562 psort(pool, data);
563 EXPECT_EQ(data, (std::vector<int>{1, 2, 3, 4, 5}));
564}
565
566TEST_F(ParallelTest, PsortLargeData)
567{
568 std::vector<int> data = large_vec;
569 std::mt19937 rng(42); // Fixed seed for reproducibility
570 std::shuffle(data.begin(), data.end(), rng);
571 psort(pool, data);
572 for (size_t i = 0; i < data.size(); ++i)
573 EXPECT_EQ(data[i], static_cast<int>(i + 1));
574}
575
576TEST_F(ParallelTest, PsortAcceptsParallelOptions)
577{
578 std::vector<int> data = {7, 1, 5, 9, 3, 2};
580 options.pool = &pool;
581 options.min_size = 2;
582 options.max_tasks = 2;
583 psort(data, std::less<int>{}, options);
584 EXPECT_EQ(data, (std::vector<int>{1, 2, 3, 5, 7, 9}));
585}
586
587TEST_F(ParallelTest, PsortHonorsCancellation)
588{
589 std::vector<int> data(4096);
590 std::iota(data.begin(), data.end(), 0);
591 std::mt19937 rng(77);
592 std::shuffle(data.begin(), data.end(), rng);
593
594 CancellationSource source;
596 options.pool = &pool;
597 options.min_size = 64;
598 options.chunk_size = 64;
599 options.cancel_token = source.token();
600 source.request_cancel();
601
602 EXPECT_THROW(psort(data, std::less<int>{}, options), operation_canceled);
603}
604
605// =============================================================================
606// pzip_for_each Tests
607// =============================================================================
608
609TEST_F(ParallelTest, PzipForEachBasic)
610{
611 std::vector<int> a = {1, 2, 3};
612 std::vector<int> b = {4, 5, 6};
613 std::atomic<int> sum{0};
614
615 pzip_for_each(pool, a, b, [&sum](int x, int y) { sum += x * y; });
616 EXPECT_EQ(sum.load(), 32); // 1*4 + 2*5 + 3*6
617}
618
619TEST_F(ParallelTest, PzipForEachDifferentLengths)
620{
621 std::vector<int> a = {1, 2, 3, 4, 5};
622 std::vector<int> b = {10, 20, 30};
623 std::atomic<int> sum{0};
624
625 pzip_for_each(pool, a, b, [&sum](int x, int y) { sum += x + y; });
626 EXPECT_EQ(sum.load(), 66); // (1+10) + (2+20) + (3+30)
627}
628
629TEST_F(ParallelTest, PzipForEachEmpty)
630{
631 std::vector<int> a;
632 std::vector<int> b = {1, 2, 3};
633 std::atomic<int> count{0};
634
635 pzip_for_each(pool, a, b, [&count](int, int) { ++count; });
636 EXPECT_EQ(count.load(), 0);
637}
638
639// =============================================================================
640// pzip_maps Tests
641// =============================================================================
642
643TEST_F(ParallelTest, PzipMapsBasic)
644{
645 std::vector<int> a = {1, 2, 3};
646 std::vector<int> b = {4, 5, 6};
647
648 auto result = pzip_maps(pool, a, b, [](int x, int y) { return x * y; });
649 EXPECT_EQ(result, (std::vector<int>{4, 10, 18}));
650}
651
652TEST_F(ParallelTest, PzipMapsTypeConversion)
653{
654 std::vector<int> a = {1, 2, 3};
655 std::vector<double> b = {1.5, 2.5, 3.5};
656
657 auto result = pzip_maps(pool, a, b, [](int x, double y) { return x + y; });
658 EXPECT_NEAR(result[0], 2.5, 0.001);
659 EXPECT_NEAR(result[1], 4.5, 0.001);
660 EXPECT_NEAR(result[2], 6.5, 0.001);
661}
662
663TEST_F(ParallelTest, ZipAlgorithmsAcceptParallelOptions)
664{
665 std::vector<int> a = {1, 2, 3, 4};
666 std::vector<int> b = {10, 20, 30, 40};
668 options.pool = &pool;
669 options.chunk_size = 2;
670
671 auto mapped = pzip_maps(a, b, [](int x, int y) { return x + y; }, options);
672 EXPECT_EQ(mapped, (std::vector<int>{11, 22, 33, 44}));
673
674 auto folded = pzip_foldl(a, b, 0, [](int acc, int x, int y) {
675 return acc + x * y;
676 }, options);
677 EXPECT_EQ(folded, 300);
678
679 std::atomic<int> visits{0};
680 pzip_for_each(a, b, [&visits](int, int) { ++visits; }, options);
681 EXPECT_EQ(visits.load(), 4);
682}
683
684// =============================================================================
685// ppartition Tests
686// =============================================================================
687
688TEST_F(ParallelTest, PpartitionBasic)
689{
690 auto [evens, odds] = ppartition(pool, small_vec, [](int x) { return x % 2 == 0; });
691 EXPECT_EQ(evens, (std::vector<int>{2, 4}));
692 EXPECT_EQ(odds, (std::vector<int>{1, 3, 5}));
693}
694
695TEST_F(ParallelTest, PpartitionAllTrue)
696{
697 auto [yes, no] = ppartition(pool, small_vec, [](int x) { return x > 0; });
698 EXPECT_EQ(yes.size(), 5u);
699 EXPECT_TRUE(no.empty());
700}
701
702TEST_F(ParallelTest, PpartitionAllFalse)
703{
704 auto [yes, no] = ppartition(pool, small_vec, [](int x) { return x < 0; });
705 EXPECT_TRUE(yes.empty());
706 EXPECT_EQ(no.size(), 5u);
707}
708
709TEST_F(ParallelTest, PpartitionEmpty)
710{
711 auto [yes, no] = ppartition(pool, empty_vec, [](int) { return true; });
712 EXPECT_TRUE(yes.empty());
713 EXPECT_TRUE(no.empty());
714}
715
716TEST_F(ParallelTest, PpartitionPreservesOrder)
717{
718 std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
719 auto [evens, odds] = ppartition(pool, data, [](int x) { return x % 2 == 0; });
720 EXPECT_EQ(evens, (std::vector<int>{2, 4, 6, 8, 10}));
721 EXPECT_EQ(odds, (std::vector<int>{1, 3, 5, 7, 9}));
722}
723
724TEST_F(ParallelTest, PpartitionAcceptsParallelOptions)
725{
727 options.pool = &pool;
728 options.chunk_size = 3;
729
730 std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8};
731 auto [evens, odds] = ppartition(data, [](int x) { return x % 2 == 0; }, options);
732 EXPECT_EQ(evens, (std::vector<int>{2, 4, 6, 8}));
733 EXPECT_EQ(odds, (std::vector<int>{1, 3, 5, 7}));
734}
735
736TEST_F(ParallelTest, PpartitionSupportsNonDefaultConstructibleValues)
737{
738 struct NoDefault
739 {
740 int value;
741
742 NoDefault() = delete;
743 explicit NoDefault(int v) : value(v) {}
744 NoDefault(const NoDefault &) = default;
745 NoDefault(NoDefault &&) noexcept = default;
746 NoDefault & operator=(const NoDefault &) = default;
747 NoDefault & operator=(NoDefault &&) noexcept = default;
748 };
749
750 std::vector<NoDefault> data;
751 for (int i = 1; i <= 6; ++i)
752 data.emplace_back(i);
753
754 auto [small, large] = ppartition(pool, data, [](const NoDefault & x) {
755 return x.value <= 3;
756 });
757
758 ASSERT_EQ(small.size(), 3u);
759 ASSERT_EQ(large.size(), 3u);
760 EXPECT_EQ(small[0].value, 1);
761 EXPECT_EQ(small[1].value, 2);
762 EXPECT_EQ(small[2].value, 3);
763 EXPECT_EQ(large[0].value, 4);
764 EXPECT_EQ(large[1].value, 5);
765 EXPECT_EQ(large[2].value, 6);
766}
767
768TEST_F(ParallelTest, PpartitionHonorsCancellation)
769{
770 CancellationSource source;
772 options.pool = &pool;
773 options.chunk_size = 16;
774 options.cancel_token = source.token();
775 source.request_cancel();
776
777 std::vector<int> data(512, 1);
778 EXPECT_THROW((void) ppartition(data, [](int x) { return x % 2 == 0; }, options),
780}
781
782TEST_F(ParallelTest, PfilterSupportsNonDefaultConstructibleValues)
783{
784 struct NoDefault
785 {
786 int value;
787
788 NoDefault() = delete;
789 explicit NoDefault(int v) : value(v) {}
790 NoDefault(const NoDefault &) = default;
791 NoDefault(NoDefault &&) noexcept = default;
792 NoDefault & operator=(const NoDefault &) = default;
793 NoDefault & operator=(NoDefault &&) noexcept = default;
794 };
795
796 std::vector<NoDefault> data;
797 for (int i = 1; i <= 8; ++i)
798 data.emplace_back(i);
799
800 auto result = pfilter(pool, data, [](const NoDefault & x) {
801 return x.value % 2 == 0;
802 });
803
804 ASSERT_EQ(result.size(), 4u);
805 EXPECT_EQ(result[0].value, 2);
806 EXPECT_EQ(result[1].value, 4);
807 EXPECT_EQ(result[2].value, 6);
808 EXPECT_EQ(result[3].value, 8);
809}
810
811// =============================================================================
812// pscan / pexclusive_scan / pmerge Tests
813// =============================================================================
814
815TEST_F(ParallelTest, PscanContainerWrapperMatchesPartialSum)
816{
817 std::vector<int> data(256);
818 std::iota(data.begin(), data.end(), 1);
819 std::vector<int> expected(data.size());
820 std::partial_sum(data.begin(), data.end(), expected.begin());
821
822 auto result = pscan(pool, data, std::plus<int>{});
823 EXPECT_EQ(result, expected);
824}
825
826TEST_F(ParallelTest, PexclusiveScanContainerWrapperWorks)
827{
828 std::vector<int> data = {1, 2, 3, 4, 5};
829 auto result = pexclusive_scan(pool, data, 0, std::plus<int>{});
830 EXPECT_EQ(result, (std::vector<int>{0, 1, 3, 6, 10}));
831}
832
833TEST_F(ParallelTest, ScanAndMergeAcceptParallelOptions)
834{
836 options.pool = &pool;
837 options.chunk_size = 8;
838
839 std::vector<int> data = {3, 1, 4, 1, 5, 9};
840 auto inclusive = pscan(data, std::plus<int>{}, options);
841 EXPECT_EQ(inclusive, (std::vector<int>{3, 4, 8, 9, 14, 23}));
842
843 auto exclusive = pexclusive_scan(data, 10, std::plus<int>{}, options);
844 EXPECT_EQ(exclusive, (std::vector<int>{10, 13, 14, 18, 19, 24}));
845
846 std::vector<int> left = {1, 3, 5, 7};
847 std::vector<int> right = {2, 4, 6, 8};
848 auto merged = pmerge(left, right, std::less<int>{}, options);
849 EXPECT_EQ(merged, (std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8}));
850}
851
852TEST_F(ParallelTest, ScanAndMergeHonorCancellation)
853{
854 CancellationSource source;
856 options.pool = &pool;
857 options.chunk_size = 16;
858 options.cancel_token = source.token();
859 source.request_cancel();
860
861 std::vector<int> data(512, 1);
862 EXPECT_THROW((void) pscan(data, std::plus<int>{}, options), operation_canceled);
863 EXPECT_THROW((void) pexclusive_scan(data, 0, std::plus<int>{}, options),
865
866 std::vector<int> left(256), right(256);
867 std::iota(left.begin(), left.end(), 0);
868 std::iota(right.begin(), right.end(), 0);
869 EXPECT_THROW((void) pmerge(left, right, std::less<int>{}, options),
871}
872
873TEST_F(ParallelTest, ScanAndMergeSupportNonDefaultConstructibleValues)
874{
875 struct NoDefault
876 {
877 int value;
878
879 NoDefault() = delete;
880 explicit NoDefault(int v) : value(v) {}
881 NoDefault(const NoDefault &) = default;
882 NoDefault(NoDefault &&) noexcept = default;
883 NoDefault & operator=(const NoDefault &) = default;
884 NoDefault & operator=(NoDefault &&) noexcept = default;
885 };
886
887 std::vector<NoDefault> data;
888 for (int i = 1; i <= 4; ++i)
889 data.emplace_back(i);
890
891 auto inclusive = pscan(data,
892 [](const NoDefault & a, const NoDefault & b) {
893 return NoDefault(a.value + b.value);
894 });
895 ASSERT_EQ(inclusive.size(), 4u);
896 EXPECT_EQ(inclusive[0].value, 1);
897 EXPECT_EQ(inclusive[1].value, 3);
898 EXPECT_EQ(inclusive[2].value, 6);
899 EXPECT_EQ(inclusive[3].value, 10);
900
901 auto exclusive = pexclusive_scan(data, NoDefault(0),
902 [](const NoDefault & a, const NoDefault & b) {
903 return NoDefault(a.value + b.value);
904 });
905 ASSERT_EQ(exclusive.size(), 4u);
906 EXPECT_EQ(exclusive[0].value, 0);
907 EXPECT_EQ(exclusive[1].value, 1);
908 EXPECT_EQ(exclusive[2].value, 3);
909 EXPECT_EQ(exclusive[3].value, 6);
910
911 std::vector<NoDefault> left, right;
912 left.emplace_back(1);
913 left.emplace_back(3);
914 left.emplace_back(5);
915 right.emplace_back(2);
916 right.emplace_back(4);
917 right.emplace_back(6);
918
919 auto merged = pmerge(left, right,
920 [](const NoDefault & a, const NoDefault & b) {
921 return a.value < b.value;
922 });
923 ASSERT_EQ(merged.size(), 6u);
924 for (size_t i = 0; i < merged.size(); ++i)
925 EXPECT_EQ(merged[i].value, static_cast<int>(i + 1));
926}
927
928// =============================================================================
929// Correctness: Sequential vs Parallel Comparison
930// =============================================================================
931
932TEST_F(ParallelTest, CorrectnessMapVsSequential)
933{
934 // Sequential
935 std::vector<int> seq_result;
936 for (int x : large_vec)
937 seq_result.push_back(x * 2 + 1);
938
939 // Parallel
940 auto par_result = pmaps(pool, large_vec, [](int x) { return x * 2 + 1; });
941
942 EXPECT_EQ(seq_result, par_result);
943}
944
945TEST_F(ParallelTest, CorrectnessFilterVsSequential)
946{
947 // Sequential
948 std::vector<int> seq_result;
949 for (int x : large_vec)
950 if (x % 17 == 0)
951 seq_result.push_back(x);
952
953 // Parallel
954 auto par_result = pfilter(pool, large_vec, [](int x) { return x % 17 == 0; });
955
956 EXPECT_EQ(seq_result, par_result);
957}
958
959TEST_F(ParallelTest, CorrectnessFoldVsSequential)
960{
961 // Sequential
962 long long seq_sum = 0;
963 for (int x : large_vec)
964 seq_sum += x;
965
966 // Parallel
967 long long par_sum = pfoldl(pool, large_vec, 0LL,
968 [](long long a, int b) { return a + b; });
969
970 EXPECT_EQ(seq_sum, par_sum);
971}
972
973// =============================================================================
974// Performance Benchmarks
975// =============================================================================
976
977namespace
978{
979 [[nodiscard]] bool parallel_benchmarks_enabled()
980 {
981 return std::getenv("ALEPH_RUN_PARALLEL_BENCHMARKS") != nullptr;
982 }
983}
984
985TEST_F(ParallelTest, BenchmarkMapSpeedup)
986{
987 if (not parallel_benchmarks_enabled())
988 GTEST_SKIP() << "Skipping timing-sensitive parallel benchmarks; "
989 << "set ALEPH_RUN_PARALLEL_BENCHMARKS=1 to enable";
990
991 std::vector<int> data(1000000);
992 std::iota(data.begin(), data.end(), 0);
993
994 // Sequential
995 auto seq_start = std::chrono::high_resolution_clock::now();
996 std::vector<int> seq_result;
997 seq_result.reserve(data.size());
998 for (int x : data)
999 seq_result.push_back(x * x + 2 * x + 1);
1000 auto seq_end = std::chrono::high_resolution_clock::now();
1001 auto seq_duration = std::chrono::duration_cast<std::chrono::microseconds>(
1002 seq_end - seq_start).count();
1003
1004 // Parallel
1005 auto par_start = std::chrono::high_resolution_clock::now();
1006 auto par_result = pmaps(pool, data, [](int x) { return x * x + 2 * x + 1; });
1007 auto par_end = std::chrono::high_resolution_clock::now();
1008 auto par_duration = std::chrono::duration_cast<std::chrono::microseconds>(
1009 par_end - par_start).count();
1010
1011 EXPECT_EQ(seq_result, par_result);
1012
1013 double speedup = static_cast<double>(seq_duration) / par_duration;
1014 std::cout << "\n=== Benchmark: pmaps ===\n";
1015 std::cout << "Data size: 1M elements\n";
1016 std::cout << "Sequential: " << seq_duration << " μs\n";
1017 std::cout << "Parallel: " << par_duration << " μs\n";
1018 std::cout << "Speedup: " << speedup << "x\n";
1019 std::cout << "========================\n\n";
1020
1021 // With multiple threads, parallel overhead may exceed benefits for trivial ops
1022 // On CI machines with limited cores or high load, speedup can be < 1.0
1023 // Use very relaxed threshold - this test validates correctness, not performance
1024 // Performance is validated by filter/sort benchmarks which have higher per-element cost
1025 if (pool.num_threads() > 1)
1026 EXPECT_GT(speedup, 0.3); // Very relaxed: just ensure parallelization isn't broken
1027}
1028
1029TEST_F(ParallelTest, BenchmarkFilterSpeedup)
1030{
1031 if (not parallel_benchmarks_enabled())
1032 GTEST_SKIP() << "Skipping timing-sensitive parallel benchmarks; "
1033 << "set ALEPH_RUN_PARALLEL_BENCHMARKS=1 to enable";
1034
1035 std::vector<int> data(1000000);
1036 std::iota(data.begin(), data.end(), 0);
1037
1038 auto pred = [](int x) { return x % 7 == 0 || x % 11 == 0; };
1039
1040 // Sequential
1041 auto seq_start = std::chrono::high_resolution_clock::now();
1042 std::vector<int> seq_result;
1043 for (int x : data)
1044 if (pred(x))
1045 seq_result.push_back(x);
1046 auto seq_end = std::chrono::high_resolution_clock::now();
1047 auto seq_duration = std::chrono::duration_cast<std::chrono::microseconds>(
1048 seq_end - seq_start).count();
1049
1050 // Parallel
1051 auto par_start = std::chrono::high_resolution_clock::now();
1052 auto par_result = pfilter(pool, data, pred);
1053 auto par_end = std::chrono::high_resolution_clock::now();
1054 auto par_duration = std::chrono::duration_cast<std::chrono::microseconds>(
1055 par_end - par_start).count();
1056
1057 EXPECT_EQ(seq_result, par_result);
1058
1059 double speedup = static_cast<double>(seq_duration) / par_duration;
1060 std::cout << "\n=== Benchmark: pfilter ===\n";
1061 std::cout << "Data size: 1M elements\n";
1062 std::cout << "Sequential: " << seq_duration << " μs\n";
1063 std::cout << "Parallel: " << par_duration << " μs\n";
1064 std::cout << "Speedup: " << speedup << "x\n";
1065 std::cout << "==========================\n\n";
1066}
1067
1068TEST_F(ParallelTest, BenchmarkSortSpeedup)
1069{
1070 if (not parallel_benchmarks_enabled())
1071 GTEST_SKIP() << "Skipping timing-sensitive parallel benchmarks; "
1072 << "set ALEPH_RUN_PARALLEL_BENCHMARKS=1 to enable";
1073
1074 std::vector<int> data(100000);
1075 std::iota(data.begin(), data.end(), 0);
1076 std::mt19937 rng(123); // Fixed seed for reproducibility
1077 std::shuffle(data.begin(), data.end(), rng);
1078
1079 std::vector<int> data_copy = data;
1080
1081 // Sequential
1082 auto seq_start = std::chrono::high_resolution_clock::now();
1083 std::sort(data.begin(), data.end());
1084 auto seq_end = std::chrono::high_resolution_clock::now();
1085 auto seq_duration = std::chrono::duration_cast<std::chrono::microseconds>(
1086 seq_end - seq_start).count();
1087
1088 // Parallel
1089 auto par_start = std::chrono::high_resolution_clock::now();
1090 psort(pool, data_copy);
1091 auto par_end = std::chrono::high_resolution_clock::now();
1092 auto par_duration = std::chrono::duration_cast<std::chrono::microseconds>(
1093 par_end - par_start).count();
1094
1095 EXPECT_EQ(data, data_copy);
1096
1097 double speedup = static_cast<double>(seq_duration) / par_duration;
1098 std::cout << "\n=== Benchmark: psort ===\n";
1099 std::cout << "Data size: 100K elements\n";
1100 std::cout << "std::sort: " << seq_duration << " μs\n";
1101 std::cout << "psort: " << par_duration << " μs\n";
1102 std::cout << "Speedup: " << speedup << "x\n";
1103 std::cout << "========================\n\n";
1104}
1105
1106// =============================================================================
1107// Thread Safety Tests
1108// =============================================================================
1109
1110TEST_F(ParallelTest, ThreadSafetyConcurrentOperations)
1111{
1112 // Run multiple parallel operations simultaneously
1113 auto future1 = std::async(std::launch::async, [this]() {
1114 return pmaps(pool, large_vec, [](int x) { return x * 2; });
1115 });
1116
1117 auto future2 = std::async(std::launch::async, [this]() {
1118 return pfilter(pool, large_vec, [](int x) { return x % 2 == 0; });
1119 });
1120
1121 auto future3 = std::async(std::launch::async, [this]() {
1122 return psum<std::vector<int>, long long>(pool, large_vec, 0LL);
1123 });
1124
1125 auto result1 = future1.get();
1126 auto result2 = future2.get();
1127 auto result3 = future3.get();
1128
1129 EXPECT_EQ(result1.size(), 10000u);
1130 EXPECT_EQ(result2.size(), 5000u);
1131 EXPECT_EQ(result3, 50005000LL);
1132}
1133
1134// =============================================================================
1135// Edge Cases
1136// =============================================================================
1137
1138TEST_F(ParallelTest, EdgeCaseSingleThread)
1139{
1140 ThreadPool single_pool(1);
1141
1142 auto result = pmaps(single_pool, small_vec, [](int x) { return x * x; });
1143 EXPECT_EQ(result, (std::vector<int>{1, 4, 9, 16, 25}));
1144}
1145
1146TEST_F(ParallelTest, EdgeCaseManyThreads)
1147{
1148 ThreadPool many_pool(16);
1149
1150 auto result = pmaps(many_pool, small_vec, [](int x) { return x * x; });
1151 EXPECT_EQ(result, (std::vector<int>{1, 4, 9, 16, 25}));
1152}
1153
1154TEST_F(ParallelTest, EdgeCaseVeryLargeData)
1155{
1156 std::vector<int> huge(100000);
1157 std::iota(huge.begin(), huge.end(), 0);
1158
1159 auto sum = psum<std::vector<int>, long long>(pool, huge, 0LL);
1160 // Sum 0..99999 = 99999*100000/2 = 4999950000
1161 EXPECT_EQ(sum, 4999950000LL);
1162}
1163
1164// =============================================================================
1165// Variadic Zip Tests (N containers)
1166// =============================================================================
1167
1168TEST_F(ParallelTest, PzipForEachN3Containers)
1169{
1170 std::vector<int> a = {1, 2, 3};
1171 std::vector<int> b = {4, 5, 6};
1172 std::vector<int> c = {7, 8, 9};
1173 std::atomic<int> sum{0};
1174
1175 pzip_for_each_n(pool, [&sum](int x, int y, int z) {
1176 sum += x + y + z;
1177 }, a, b, c);
1178
1179 EXPECT_EQ(sum.load(), 45); // (1+4+7) + (2+5+8) + (3+6+9)
1180}
1181
1182TEST_F(ParallelTest, PzipForEachN4Containers)
1183{
1184 std::vector<int> a = {1, 2};
1185 std::vector<int> b = {3, 4};
1186 std::vector<int> c = {5, 6};
1187 std::vector<int> d = {7, 8};
1188 std::atomic<int> sum{0};
1189
1190 pzip_for_each_n(pool, [&sum](int w, int x, int y, int z) {
1191 sum += w * x * y * z;
1192 }, a, b, c, d);
1193
1194 EXPECT_EQ(sum.load(), 1*3*5*7 + 2*4*6*8); // 105 + 384 = 489
1195}
1196
1197TEST_F(ParallelTest, PzipForEachNDifferentLengths)
1198{
1199 std::vector<int> a = {1, 2, 3, 4, 5};
1200 std::vector<int> b = {10, 20, 30};
1201 std::vector<int> c = {100, 200, 300, 400};
1202 std::atomic<int> count{0};
1203
1204 pzip_for_each_n(pool, [&count](int, int, int) {
1205 ++count;
1206 }, a, b, c);
1207
1208 EXPECT_EQ(count.load(), 3); // Min length
1209}
1210
1211TEST_F(ParallelTest, PzipMapsN3Containers)
1212{
1213 std::vector<int> a = {1, 2, 3};
1214 std::vector<int> b = {4, 5, 6};
1215 std::vector<int> c = {7, 8, 9};
1216
1217 auto result = pzip_maps_n(pool, [](int x, int y, int z) {
1218 return x + y + z;
1219 }, a, b, c);
1220
1221 EXPECT_EQ(result, (std::vector<int>{12, 15, 18}));
1222}
1223
1224TEST_F(ParallelTest, PzipMapsNEmpty)
1225{
1226 std::vector<int> a;
1227 std::vector<int> b = {1, 2, 3};
1228
1229 auto result = pzip_maps_n(pool, [](int x, int y) {
1230 return x + y;
1231 }, a, b);
1232
1233 EXPECT_TRUE(result.empty());
1234}
1235
1236TEST_F(ParallelTest, PzipFoldlNVariadic)
1237{
1238 std::vector<int> a = {1, 2, 3};
1239 std::vector<int> b = {4, 5, 6};
1240
1241 // Dot product using variadic version with combiner
1242 int dot = pzip_foldl_n(pool, 0,
1243 [](int acc, int x, int y) { return acc + x * y; },
1244 std::plus<int>(),
1245 a, b);
1246
1247 EXPECT_EQ(dot, 32); // 1*4 + 2*5 + 3*6
1248}
1249
1250TEST_F(ParallelTest, PzipAllN3ContainersTrue)
1251{
1252 std::vector<int> a = {1, 2, 3};
1253 std::vector<int> b = {2, 3, 4};
1254 std::vector<int> c = {3, 4, 5};
1255
1256 bool result = pzip_all_n(pool, [](int x, int y, int z) {
1257 return x < y && y < z;
1258 }, a, b, c);
1259
1260 EXPECT_TRUE(result);
1261}
1262
1263TEST_F(ParallelTest, PzipAllN3ContainersFalse)
1264{
1265 std::vector<int> a = {1, 2, 3};
1266 std::vector<int> b = {2, 3, 4};
1267 std::vector<int> c = {3, 2, 5}; // 2 < 3 is true, but 3 < 2 is false
1268
1269 bool result = pzip_all_n(pool, [](int x, int y, int z) {
1270 return x < y && y < z;
1271 }, a, b, c);
1272
1273 EXPECT_FALSE(result);
1274}
1275
1276TEST_F(ParallelTest, PzipExistsNTrue)
1277{
1278 std::vector<int> a = {1, 2, 3};
1279 std::vector<int> b = {4, 2, 6};
1280
1281 bool result = pzip_exists_n(pool, [](int x, int y) {
1282 return x == y;
1283 }, a, b);
1284
1285 EXPECT_TRUE(result); // 2 == 2
1286}
1287
1288TEST_F(ParallelTest, PzipExistsNFalse)
1289{
1290 std::vector<int> a = {1, 2, 3};
1291 std::vector<int> b = {4, 5, 6};
1292
1293 bool result = pzip_exists_n(pool, [](int x, int y) {
1294 return x == y;
1295 }, a, b);
1296
1297 EXPECT_FALSE(result);
1298}
1299
1300TEST_F(ParallelTest, PzipCountIfN)
1301{
1302 std::vector<int> a = {1, 2, 3, 4, 5};
1303 std::vector<int> b = {5, 4, 3, 2, 1};
1304
1305 size_t count = pzip_count_if_n(pool, [](int x, int y) {
1306 return x + y == 6;
1307 }, a, b);
1308
1309 EXPECT_EQ(count, 5u); // All pairs sum to 6
1310}
1311
1312TEST_F(ParallelTest, PzipCountIfNPartial)
1313{
1314 std::vector<int> a = {1, 2, 3, 4, 5};
1315 std::vector<int> b = {1, 2, 3, 4, 5};
1316
1317 size_t count = pzip_count_if_n(pool, [](int x, int y) {
1318 return x == y && x % 2 == 0;
1319 }, a, b);
1320
1321 EXPECT_EQ(count, 2u); // 2 and 4
1322}
1323
1324TEST_F(ParallelTest, VariadicZipAlgorithmsAcceptParallelOptions)
1325{
1326 std::vector<int> a = {1, 2, 3};
1327 std::vector<int> b = {4, 5, 6};
1328 std::vector<int> c = {7, 8, 9};
1330 options.pool = &pool;
1331 options.chunk_size = 1;
1332
1333 auto mapped = pzip_maps_n([](int x, int y, int z) { return x + y + z; },
1334 options, a, b, c);
1335 EXPECT_EQ(mapped, (std::vector<int>{12, 15, 18}));
1336
1337 auto folded = pzip_foldl_n(0,
1338 [](int acc, int x, int y, int z) {
1339 return acc + x + y + z;
1340 },
1341 std::plus<int>{},
1342 options, a, b, c);
1343 EXPECT_EQ(folded, 45);
1344
1345 EXPECT_TRUE(pzip_all_n([](int x, int y, int z) { return x < y && y < z; },
1346 options, a, b, c));
1347 EXPECT_TRUE(pzip_exists_n([](int x, int y, int z) { return x + y + z == 15; },
1348 options, a, b, c));
1349 EXPECT_EQ(pzip_count_if_n([](int x, int y, int z) { return x + y + z > 14; },
1350 options, a, b, c),
1351 2u);
1352}
1353
1354// =============================================================================
1355// Enumerate Tests
1356// =============================================================================
1357
1358TEST_F(ParallelTest, PenumerateForEachModify)
1359{
1360 std::vector<int> data(100, 0);
1361
1362 penumerate_for_each(pool, data, [](size_t i, int& x) {
1363 x = static_cast<int>(i * 2);
1364 });
1365
1366 for (size_t i = 0; i < data.size(); ++i)
1367 EXPECT_EQ(data[i], static_cast<int>(i * 2));
1368}
1369
1370TEST_F(ParallelTest, PenumerateForEachConst)
1371{
1372 const std::vector<int> data = {10, 20, 30, 40, 50};
1373 std::atomic<int> weighted_sum{0};
1374
1375 penumerate_for_each(pool, data, [&weighted_sum](size_t i, int x) {
1376 weighted_sum += static_cast<int>(i) * x;
1377 });
1378
1379 // 0*10 + 1*20 + 2*30 + 3*40 + 4*50 = 0 + 20 + 60 + 120 + 200 = 400
1380 EXPECT_EQ(weighted_sum.load(), 400);
1381}
1382
1383TEST_F(ParallelTest, PenumerateMaps)
1384{
1385 std::vector<std::string> words = {"a", "bb", "ccc"};
1386
1387 auto result = penumerate_maps(pool, words,
1388 [](size_t i, const std::string& s) {
1389 return std::to_string(i) + ":" + s;
1390 });
1391
1392 EXPECT_EQ(result[0], "0:a");
1393 EXPECT_EQ(result[1], "1:bb");
1394 EXPECT_EQ(result[2], "2:ccc");
1395}
1396
1397TEST_F(ParallelTest, PenumerateMapsEmpty)
1398{
1399 std::vector<int> empty;
1400
1401 auto result = penumerate_maps(pool, empty,
1402 [](size_t i, int x) { return static_cast<int>(i + x); });
1403
1404 EXPECT_TRUE(result.empty());
1405}
1406
1407TEST_F(ParallelTest, PenumerateAcceptsParallelOptions)
1408{
1409 std::vector<int> data(6, 0);
1411 options.pool = &pool;
1412 options.chunk_size = 2;
1413
1414 penumerate_for_each(data, [](size_t i, int & x) {
1415 x = static_cast<int>(i + 10);
1416 }, options);
1417 EXPECT_EQ(data, (std::vector<int>{10, 11, 12, 13, 14, 15}));
1418
1419 auto labels = penumerate_maps(data, [](size_t i, int x) {
1420 return std::to_string(i) + "=" + std::to_string(x);
1421 }, options);
1422 EXPECT_EQ(labels[0], "0=10");
1423 EXPECT_EQ(labels[5], "5=15");
1424}
1425
1426TEST_F(ParallelTest, ZipAndEnumerateHonorCancellation)
1427{
1428 std::vector<int> a(256, 1), b(256, 2), c(256, 3);
1429 CancellationSource source;
1431 options.pool = &pool;
1432 options.chunk_size = 16;
1433 options.cancel_token = source.token();
1434 source.request_cancel();
1435
1436 EXPECT_THROW((void) pzip_maps(a, b, [](int x, int y) { return x + y; }, options),
1438 EXPECT_THROW((void) pzip_maps_n([](int x, int y, int z) { return x + y + z; },
1439 options, a, b, c),
1441 EXPECT_THROW((void) penumerate_maps(a, [](size_t i, int x) {
1442 return static_cast<int>(i) + x;
1443 }, options),
1445}
1446
1447// =============================================================================
1448// Large Data Variadic Tests
1449// =============================================================================
1450
1451TEST_F(ParallelTest, PzipForEachNLargeData)
1452{
1453 std::vector<int> a(10000), b(10000), c(10000);
1454 std::iota(a.begin(), a.end(), 0);
1455 std::iota(b.begin(), b.end(), 10000);
1456 std::iota(c.begin(), c.end(), 20000);
1457
1458 std::atomic<long long> sum{0};
1459
1460 pzip_for_each_n(pool, [&sum](int x, int y, int z) {
1461 sum += x + y + z;
1462 }, a, b, c);
1463
1464 // Sum of 0..9999 + 10000..19999 + 20000..29999
1465 // = 3 * (0+1+...+9999) + 10000*10000 + 20000*10000
1466 // = 3 * 49995000 + 100000000 + 200000000
1467 // = 149985000 + 300000000 = 449985000
1468 EXPECT_EQ(sum.load(), 449985000LL);
1469}
1470
1471TEST_F(ParallelTest, PzipMapsNLargeData)
1472{
1473 std::vector<int> a(10000), b(10000);
1474 std::iota(a.begin(), a.end(), 0);
1475 std::iota(b.begin(), b.end(), 0);
1476
1477 auto result = pzip_maps_n(pool, [](int x, int y) {
1478 return x * y;
1479 }, a, b);
1480
1481 for (size_t i = 0; i < result.size(); ++i)
1482 EXPECT_EQ(result[i], static_cast<int>(i * i));
1483}
1484
1485TEST_F(ParallelTest, CorrectnessZipNVsSequential)
1486{
1487 std::vector<int> a(1000), b(1000), c(1000);
1488 std::iota(a.begin(), a.end(), 0);
1489 std::iota(b.begin(), b.end(), 1000);
1490 std::iota(c.begin(), c.end(), 2000);
1491
1492 // Sequential
1493 std::vector<int> seq_result;
1494 for (size_t i = 0; i < a.size(); ++i)
1495 seq_result.push_back(a[i] + b[i] + c[i]);
1496
1497 // Parallel
1498 auto par_result = pzip_maps_n(pool, [](int x, int y, int z) {
1499 return x + y + z;
1500 }, a, b, c);
1501
1502 EXPECT_EQ(seq_result, par_result);
1503}
1504
1505int main(int argc, char **argv)
1506{
1507 ::testing::InitGoogleTest(&argc, argv);
1508 return RUN_ALL_TESTS();
1509}
Parallel functional programming operations using ThreadPool.
TEST_F(ParallelTest, PmapsSquare)
int main()
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
Cooperative cancellation source paired with CancellationToken.
A reusable thread pool for efficient parallel task execution.
Minimal std::expected-style result type for C++20.
Exception thrown when cooperative cancellation is observed.
std::vector< int > single_vec
void SetUp() override
std::vector< int > empty_vec
std::vector< int > small_vec
std::vector< int > large_vec
static mt19937 rng
Freq_Node * pred
Predecessor node in level-order traversal.
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
bool pall(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel all predicate (short-circuit).
bool pnone(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel none predicate.
auto pmaps(ThreadPool &pool, const Container &c, Op op, size_t chunk_size=0)
Parallel map operation.
auto pmin(ThreadPool &pool, const Container &c, size_t chunk_size=0)
Parallel minimum element.
T pzip_foldl_n(ThreadPool &pool, T init, Op op, Combiner combiner, const Containers &... cs)
Parallel fold/reduce over N zipped containers (variadic).
T pzip_foldl(ThreadPool &pool, const Container1 &c1, const Container2 &c2, T init, Op op, size_t chunk_size=0)
Parallel zip + fold.
void pzip_for_each(ThreadPool &pool, const Container1 &c1, const Container2 &c2, Op op, size_t chunk_size=0)
Parallel zip + for_each.
auto penumerate_maps(ThreadPool &pool, const Container &c, Op op, size_t chunk_size=0)
Parallel enumerate with map.
void penumerate_for_each(ThreadPool &pool, Container &c, Op op, size_t chunk_size=0)
Parallel for_each with index (enumerate).
bool pzip_all_n(ThreadPool &pool, Pred pred, const Containers &... cs)
Parallel all predicate over N zipped containers (variadic).
size_t pcount_if(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel count_if operation.
auto pexclusive_scan(ThreadPool &pool, const Container &c, T init, BinaryOp op, size_t chunk_size=0)
Parallel exclusive scan over a container.
std::optional< size_t > pfind(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel find operation (returns index).
bool pzip_exists_n(ThreadPool &pool, Pred pred, const Containers &... cs)
Parallel exists predicate over N zipped containers (variadic).
void psort(ThreadPool &pool, Container &c, Compare cmp=Compare{}, const size_t min_parallel_size=1024)
Parallel sort (in-place).
void pfor_each(ThreadPool &pool, Container &c, Op op, size_t chunk_size=0)
Parallel for_each operation.
auto pfilter(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel filter operation.
auto ppartition(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel partition (stable).
auto pmerge(ThreadPool &pool, const Container1 &c1, const Container2 &c2, Compare comp=Compare{}, size_t chunk_size=0)
Parallel merge of two sorted containers.
T pproduct(ThreadPool &pool, const Container &c, T init=T{1}, size_t chunk_size=0)
Parallel product of elements.
T product(const Container &container, const T &init=T{1})
Compute product of all elements.
auto pmax(ThreadPool &pool, const Container &c, size_t chunk_size=0)
Parallel maximum element.
void pzip_for_each_n(ThreadPool &pool, Op op, const Containers &... cs)
Parallel for_each over N zipped containers (variadic).
auto pzip_maps_n(ThreadPool &pool, Op op, const Containers &... cs)
Parallel map over N zipped containers (variadic).
auto pscan(ThreadPool &pool, const Container &c, BinaryOp op, size_t chunk_size=0)
Parallel inclusive scan over a container.
T pfoldl(ThreadPool &pool, const Container &c, T init, BinaryOp op, size_t chunk_size=0)
Parallel left fold (reduce).
auto pfind_value(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel find with value return.
auto pzip_maps(ThreadPool &pool, const Container1 &c1, const Container2 &c2, Op op, size_t chunk_size=0)
Parallel zip + map.
T psum(ThreadPool &pool, const Container &c, T init=T{}, size_t chunk_size=0)
Parallel sum of elements.
auto pminmax(ThreadPool &pool, const Container &c, size_t chunk_size=0)
Parallel min and max elements.
size_t pzip_count_if_n(ThreadPool &pool, Pred pred, const Containers &... cs)
Parallel count over N zipped containers (variadic).
bool pexists(ThreadPool &pool, const Container &c, Pred pred, size_t chunk_size=0)
Parallel exists predicate (short-circuit).
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
static struct argp_option options[]
Definition ntreepic.C:1890
#define LL
Definition ran_array.c:24
Common configuration object for parallel algorithms.
size_t chunk_size
Elements per chunk (0 = auto).
ThreadPool * pool
Executor to use (nullptr = default_pool()).