Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
concurrency_utils_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31#include <gtest/gtest.h>
32
33#include <concurrency_utils.H>
34#include <thread_pool.H>
35
36#include <algorithm>
37#include <atomic>
38#include <chrono>
39#include <cstring>
40#include <future>
41#include <memory>
42#include <numeric>
43#include <random>
44#include <stdexcept>
45#include <thread>
46#include <vector>
47
48using namespace Aleph;
49using namespace std::chrono_literals;
50
51namespace
52{
53 template <typename Sync>
55 requires(Sync sync)
56 {
57 sync.with_lock([](auto & value) { return value; });
58 };
59
60 template <typename Sync>
62 requires(Sync sync)
63 {
64 sync.with_read_lock([](const auto & value) { return value; });
65 };
66
67 template <typename Sync>
69 requires(Sync sync)
70 {
71 sync.with_write_lock([](auto & value) { return value; });
72 };
73
74 struct TokenPayload
75 {
77 int value;
78
79 TokenPayload(CancellationToken token_arg, int value_arg)
80 : token(std::move(token_arg)), value(value_arg) {}
81 };
82
83 struct ExceptionSafePayload
84 {
85 static inline bool throw_on_move_construction = false;
86 static inline bool throw_on_move_assignment = false;
87
88 int value = 0;
89
90 ExceptionSafePayload() = default;
91
92 explicit ExceptionSafePayload(int value_arg)
93 : value(value_arg) {}
94
95 ExceptionSafePayload(const ExceptionSafePayload &) = default;
96 ExceptionSafePayload & operator = (const ExceptionSafePayload &) = default;
97
98 ExceptionSafePayload(ExceptionSafePayload && other)
99 : value(other.value)
100 {
101 other.value = -1;
102 if (throw_on_move_construction)
103 throw std::runtime_error("move construction failed");
104 }
105
106 ExceptionSafePayload & operator = (ExceptionSafePayload && other)
107 {
108 value = other.value;
109 other.value = -1;
110 if (throw_on_move_assignment)
111 throw std::runtime_error("move assignment failed");
112 return *this;
113 }
114
115 static void reset_failures() noexcept
116 {
117 throw_on_move_construction = false;
118 throw_on_move_assignment = false;
119 }
120 };
121}
122
123static_assert(SupportsValueReturningWithLock<synchronized<int>>);
124static_assert(SupportsValueReturningWithReadLock<rw_synchronized<int>>);
125static_assert(SupportsValueReturningWithWriteLock<rw_synchronized<int>>);
126
127TEST(ConcurrencyUtils, BoundedChannelCloseDrainsQueuedItems)
128{
130
131 ASSERT_TRUE(ch.send(10));
132 ASSERT_TRUE(ch.send(20));
133 ch.close();
134
135 auto first = ch.recv();
136 auto second = ch.recv();
137 auto third = ch.recv();
138
139 ASSERT_TRUE(first.has_value());
140 ASSERT_TRUE(second.has_value());
141 EXPECT_EQ(*first, 10);
142 EXPECT_EQ(*second, 20);
143 EXPECT_FALSE(third.has_value());
144 EXPECT_FALSE(ch.send(30));
145}
146
147TEST(ConcurrencyUtils, BoundedChannelTrySendAndTryRecv)
148{
150
151 EXPECT_TRUE(ch.try_send(7));
152 EXPECT_FALSE(ch.try_send(8));
153
154 auto first = ch.try_recv();
155 auto second = ch.try_recv();
156
157 ASSERT_TRUE(first.has_value());
158 EXPECT_EQ(*first, 7);
159 EXPECT_FALSE(second.has_value());
160}
161
162TEST(ConcurrencyUtils, BoundedChannelCloseUnblocksSenderAndReceiver)
163{
164 bounded_channel<int> full_ch(1);
165 ASSERT_TRUE(full_ch.send(1));
166
167 std::atomic<bool> sender_entered{false};
168 std::promise<bool> sender_result;
169 auto sender_future = sender_result.get_future();
170 std::thread sender([&] {
171 sender_entered.store(true, std::memory_order_release);
172 sender_result.set_value(full_ch.send(2));
173 });
174
175 while (not sender_entered.load(std::memory_order_acquire))
176 std::this_thread::yield();
177 full_ch.close();
178 EXPECT_FALSE(sender_future.get());
179 sender.join();
180
181 bounded_channel<int> empty_ch(1);
182 std::atomic<bool> receiver_entered{false};
183 std::promise<std::optional<int>> receiver_result;
184 auto receiver_future = receiver_result.get_future();
185 std::thread receiver([&] {
186 receiver_entered.store(true, std::memory_order_release);
187 receiver_result.set_value(empty_ch.recv());
188 });
189
190 while (not receiver_entered.load(std::memory_order_acquire))
191 std::this_thread::yield();
192 empty_ch.close();
193 EXPECT_FALSE(receiver_future.get().has_value());
194 receiver.join();
195}
196
197TEST(ConcurrencyUtils, BoundedChannelProducerConsumerPreservesOrder)
198{
200 std::vector<int> received;
201 received.reserve(2000);
202 std::atomic<bool> producer_ok{true};
203
204 std::thread producer([&] {
205 for (int i = 0; i < 2000; ++i)
206 if (not ch.send(i))
207 producer_ok.store(false, std::memory_order_relaxed);
208 ch.close();
209 });
210
211 std::thread consumer([&] {
212 while (auto item = ch.recv())
213 received.push_back(*item);
214 });
215
216 producer.join();
217 consumer.join();
218
219 EXPECT_TRUE(producer_ok.load(std::memory_order_relaxed));
220 ASSERT_EQ(received.size(), 2000u);
221 for (size_t i = 0; i < received.size(); ++i)
222 EXPECT_EQ(received[i], static_cast<int>(i));
223}
224
225TEST(ConcurrencyUtils, BoundedChannelSupportsMoveOnlyPayloads)
226{
228
229 ASSERT_TRUE(ch.send(std::make_unique<int>(42)));
230 auto item = ch.recv();
231
232 ASSERT_TRUE(item.has_value());
233 ASSERT_TRUE(item->get() != nullptr);
234 EXPECT_EQ(**item, 42);
235}
236
237TEST(ConcurrencyUtils, BoundedChannelCancellationInterruptsBlockedSend)
238{
240 CancellationSource source;
241 ASSERT_TRUE(ch.send(1));
242
243 std::atomic<bool> started{false};
244 std::promise<bool> canceled;
245 auto future = canceled.get_future();
246
247 std::thread sender([&] {
248 started.store(true, std::memory_order_release);
249 try
250 {
251 (void) ch.send(2, source.token());
252 canceled.set_value(false);
253 }
254 catch (const operation_canceled &)
255 {
256 canceled.set_value(true);
257 }
258 });
259
260 while (not started.load(std::memory_order_acquire))
261 std::this_thread::yield();
262 std::this_thread::sleep_for(5ms);
263 source.request_cancel();
264
265 EXPECT_TRUE(future.get());
266 sender.join();
267}
268
269TEST(ConcurrencyUtils, BoundedChannelCancellationInterruptsBlockedRecv)
270{
272 CancellationSource source;
273
274 std::atomic<bool> started{false};
275 std::promise<bool> canceled;
276 auto future = canceled.get_future();
277
278 std::thread receiver([&] {
279 started.store(true, std::memory_order_release);
280 try
281 {
282 (void) ch.recv(source.token());
283 canceled.set_value(false);
284 }
285 catch (const operation_canceled &)
286 {
287 canceled.set_value(true);
288 }
289 });
290
291 while (not started.load(std::memory_order_acquire))
292 std::this_thread::yield();
293 std::this_thread::sleep_for(5ms);
294 source.request_cancel();
295
296 EXPECT_TRUE(future.get());
297 receiver.join();
298}
299
300// A cancellation that notified without the mutex of the channel could come
301// between the check of the token and the wait of a blocked operation, and be
302// lost; the operation then slept on until something else happened on the
303// channel (7.0.1 checked the token every 10 ms instead). Now the cancellation
304// takes the mutex before it notifies. Each round cancels a send or a recv
305// that is about to block, at varying times.
306TEST(ConcurrencyUtils, BoundedChannelNeverMissesTheCancellation)
307{
308 std::mt19937 rng(20261015);
309 std::atomic<unsigned> sink{0};
310 for (int round = 0; round < 5000; ++round)
311 {
313 const bool sending = round % 2 == 1;
314 if (sending)
315 ASSERT_TRUE(ch.send(0)); // full, so the next send blocks
316
317 CancellationSource source;
318 std::atomic<bool> started{false};
319 std::promise<void> done;
320 auto finished = done.get_future();
321 std::thread blocked([&] {
322 started.store(true);
323 try
324 {
325 if (sending)
326 (void) ch.send(1, source.token());
327 else
328 (void) ch.recv(source.token());
329 }
330 catch (const operation_canceled &)
331 {
332 }
333 done.set_value();
334 });
335
336 while (not started.load())
337 std::this_thread::yield();
338 for (unsigned k = 0, n = rng() % 60; k < n; ++k)
339 sink.fetch_add(1, std::memory_order_relaxed);
340 source.request_cancel();
341
342 // a watchdog, far longer than the channel takes to see the cancellation
343 const bool seen = finished.wait_for(10s) == std::future_status::ready;
344 if (not seen)
345 ch.close(); // let the blocked operation go
346 blocked.join();
347 ASSERT_TRUE(seen) << "round " << round << " missed the cancellation";
348 }
349}
350
351// With the cancellation already requested, an operation that can proceed
352// does, and one that would have to wait throws instead, without waiting.
353TEST(ConcurrencyUtils, BoundedChannelCanceledTokenThrowsInsteadOfWaiting)
354{
356 CancellationSource source;
357 source.request_cancel();
358 const auto token = source.token();
359
360 int out = 0;
361 EXPECT_THROW((void) ch.recv(token), operation_canceled);
362 EXPECT_THROW((void) ch.recv(out, token), operation_canceled);
363 EXPECT_TRUE(ch.send(1, token));
364 EXPECT_THROW((void) ch.send(2, token), operation_canceled);
365 EXPECT_THROW((void) ch.emplace(token, 3), operation_canceled);
366 EXPECT_EQ(ch.size(), 1u);
367 EXPECT_TRUE(ch.recv(out, token));
368 EXPECT_EQ(out, 1);
369}
370
371TEST(ConcurrencyUtils, BoundedChannelCloseWinsIfOperationCanProceed)
372{
374 CancellationSource source;
375
376 ASSERT_TRUE(ch.send(11));
377 ch.close();
378 source.request_cancel();
379
380 auto first = ch.recv(source.token());
381 auto second = ch.recv(source.token());
382
383 ASSERT_TRUE(first.has_value());
384 EXPECT_EQ(*first, 11);
385 EXPECT_FALSE(second.has_value());
386}
387
388TEST(ConcurrencyUtils, BoundedChannelCancellationAppliesToEmplace)
389{
391 CancellationSource source;
392 ASSERT_TRUE(ch.send(1));
393
394 std::atomic<bool> started{false};
395 std::promise<bool> canceled;
396 auto future = canceled.get_future();
397
398 std::thread producer([&] {
399 started.store(true, std::memory_order_release);
400 try
401 {
402 (void) ch.emplace(source.token(), 2);
403 canceled.set_value(false);
404 }
405 catch (const operation_canceled &)
406 {
407 canceled.set_value(true);
408 }
409 });
410
411 while (not started.load(std::memory_order_acquire))
412 std::this_thread::yield();
413 std::this_thread::sleep_for(5ms);
414 source.request_cancel();
415
416 EXPECT_TRUE(future.get());
417 producer.join();
418}
419
420TEST(ConcurrencyUtils, BoundedChannelEmplaceAcceptsCancellationTokenPayloads)
421{
423 CancellationSource source;
424 auto token = source.token();
425
426 ASSERT_TRUE(ch.emplace(token, 42));
427
428 auto received = ch.recv();
429 ASSERT_TRUE(received.has_value());
430 EXPECT_EQ(received->value, 42);
431 EXPECT_FALSE(received->token.stop_requested());
432
433 source.request_cancel();
434
435 EXPECT_TRUE(received->token.stop_requested());
436}
437
438TEST(ConcurrencyUtils, BoundedChannelRecvUsesCopyFallbackForThrowingMoves)
439{
440 ExceptionSafePayload::reset_failures();
441
443 ASSERT_TRUE(ch.send(ExceptionSafePayload(23)));
444
445 ExceptionSafePayload::throw_on_move_construction = true;
446 auto received = ch.recv();
447 ExceptionSafePayload::reset_failures();
448
449 ASSERT_TRUE(received.has_value());
450 EXPECT_EQ(received->value, 23);
451}
452
453TEST(ConcurrencyUtils, BoundedChannelTryRecvPreservesQueuedValueOnAssignmentFailure)
454{
455 ExceptionSafePayload::reset_failures();
456
458 ASSERT_TRUE(ch.send(ExceptionSafePayload(17)));
459
460 ExceptionSafePayload out;
461 ExceptionSafePayload::throw_on_move_assignment = true;
462 EXPECT_THROW((void) ch.try_recv(out), std::runtime_error);
463 ExceptionSafePayload::reset_failures();
464
465 auto recovered = ch.recv();
466 ASSERT_TRUE(recovered.has_value());
467 EXPECT_EQ(recovered->value, 17);
468}
469
470// A Synchronized or RwSynchronized built by default value-initializes its
471// value: zero for a scalar, which was indeterminate. Built over a buffer
472// with garbage, so that an indeterminate value would show (Coverity Scan
473// of 7.7.3, UNINIT_CTOR)
474TEST(ConcurrencyUtils, DefaultValueIsValueInitialized)
475{
476 {
477 alignas(Synchronized<long>) unsigned char buf[sizeof(Synchronized<long>)];
478 std::memset(buf, 0x5a, sizeof(buf));
479 auto * p = ::new (static_cast<void *>(buf)) Synchronized<long>;
480 EXPECT_EQ(p->with_lock([] (const long & v) { return v; }), 0);
481 p->~Synchronized<long>();
482 }
483 {
484 alignas(RwSynchronized<long>) unsigned char buf[sizeof(RwSynchronized<long>)];
485 std::memset(buf, 0x5a, sizeof(buf));
486 auto * p = ::new (static_cast<void *>(buf)) RwSynchronized<long>;
487 EXPECT_EQ(p->with_read_lock([] (const long & v) { return v; }), 0);
488 p->~RwSynchronized<long>();
489 }
491 EXPECT_EQ(q.with_lock([] (double * const & v) { return v; }), nullptr);
492}
493
494TEST(ConcurrencyUtils, SynchronizedWithLockAndGuard)
495{
496 synchronized<std::vector<int>> values(std::in_place);
497
498 values.with_lock([](auto & v) {
499 v.push_back(1);
500 v.push_back(2);
501 });
502
503 {
504 auto locked = values.lock();
505 locked->push_back(3);
506 }
507
508 const auto copy = values.with_lock([](const auto & v) {
509 return v;
510 });
511
512 EXPECT_EQ(copy, (std::vector<int>{1, 2, 3}));
513}
514
515TEST(ConcurrencyUtils, SynchronizedCounterUnderContention)
516{
517 ThreadPool pool(4);
518 TaskGroup group(pool);
520
521 for (int worker = 0; worker < 8; ++worker)
522 group.launch([&] {
523 for (int i = 0; i < 2000; ++i)
524 counter.with_lock([](int & value) { ++value; });
525 });
526
527 group.wait();
528
529 EXPECT_EQ(counter.with_lock([](const int & value) { return value; }), 16000);
530}
531
532TEST(ConcurrencyUtils, RwSynchronizedSupportsReadAndWriteAccess)
533{
534 rw_synchronized<std::vector<int>> values(std::in_place);
535
536 values.with_write_lock([](auto & v) {
537 v.push_back(4);
538 v.push_back(5);
539 });
540
541 {
542 auto write_locked = values.write();
543 write_locked->push_back(6);
544 }
545
546 {
547 auto read_locked = values.read();
548 ASSERT_EQ(read_locked->size(), 3u);
549 EXPECT_EQ((*read_locked)[0], 4);
550 EXPECT_EQ((*read_locked)[2], 6);
551 }
552
553 EXPECT_EQ(values.with_read_lock([](const auto & v) {
554 return std::accumulate(v.begin(), v.end(), 0);
555 }), 15);
556}
557
558TEST(ConcurrencyUtils, SynchronizedSupportsNonDefaultConstructibleValues)
559{
560 struct Payload
561 {
562 explicit Payload(int x) : value(x) {}
563 int value;
564 };
565
566 synchronized<Payload> payload(std::in_place, 7);
567 payload.with_lock([](Payload & p) { p.value += 5; });
568 EXPECT_EQ(payload.with_lock([](const Payload & p) { return p.value; }), 12);
569}
570
571TEST(ConcurrencyUtils, RwSynchronizedSupportsNonDefaultConstructibleValues)
572{
573 struct Payload
574 {
575 explicit Payload(int x) : value(x) {}
576 int value;
577 };
578
579 rw_synchronized<Payload> payload(std::in_place, 9);
580 payload.with_write_lock([](Payload & p) { p.value *= 2; });
581 EXPECT_EQ(payload.with_read_lock([](const Payload & p) { return p.value; }), 18);
582}
583
584TEST(ConcurrencyUtils, SpscQueueBasicPushPop)
585{
586 spsc_queue<int> queue(3);
587
588 EXPECT_TRUE(queue.try_push(1));
589 EXPECT_TRUE(queue.try_push(2));
590 EXPECT_TRUE(queue.try_push(3));
591 EXPECT_FALSE(queue.try_push(4));
592 EXPECT_TRUE(queue.full());
593
594 auto first = queue.try_pop();
595 auto second = queue.try_pop();
596 auto third = queue.try_pop();
597 auto fourth = queue.try_pop();
598
599 ASSERT_TRUE(first.has_value());
600 ASSERT_TRUE(second.has_value());
601 ASSERT_TRUE(third.has_value());
602 EXPECT_EQ(*first, 1);
603 EXPECT_EQ(*second, 2);
604 EXPECT_EQ(*third, 3);
605 EXPECT_FALSE(fourth.has_value());
606 EXPECT_TRUE(queue.empty());
607}
608
609TEST(ConcurrencyUtils, SpscQueueProducerConsumerRoundTrip)
610{
611 spsc_queue<int> queue(64);
612 std::vector<int> received;
613 received.reserve(5000);
614
615 std::thread producer([&] {
616 for (int i = 0; i < 5000; ++i)
617 while (not queue.try_push(i))
618 std::this_thread::yield();
619 });
620
621 std::thread consumer([&] {
622 while (received.size() < 5000)
623 {
624 auto item = queue.try_pop();
625 if (item.has_value())
626 received.push_back(*item);
627 else
628 std::this_thread::yield();
629 }
630 });
631
632 producer.join();
633 consumer.join();
634
635 ASSERT_EQ(received.size(), 5000u);
636 for (size_t i = 0; i < received.size(); ++i)
637 EXPECT_EQ(received[i], static_cast<int>(i));
638}
639
640TEST(ConcurrencyUtils, SpscQueueSupportsMoveOnlyValues)
641{
643
644 ASSERT_TRUE(queue.try_push(std::make_unique<int>(42)));
645 auto item = queue.try_pop();
646
647 ASSERT_TRUE(item.has_value());
648 ASSERT_TRUE(item->get() != nullptr);
649 EXPECT_EQ(**item, 42);
650}
651
652TEST(ConcurrencyUtils, SpscQueueTryPopUsesCopyFallbackForThrowingMoves)
653{
654 ExceptionSafePayload::reset_failures();
655
657 ASSERT_TRUE(queue.try_push(ExceptionSafePayload(31)));
658
659 ExceptionSafePayload::throw_on_move_construction = true;
660 auto item = queue.try_pop();
661 ExceptionSafePayload::reset_failures();
662
663 ASSERT_TRUE(item.has_value());
664 EXPECT_EQ(item->value, 31);
665}
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Bounded blocking channel for producer-consumer workflows.
bool emplace(Args &&... args)
Construct an element in-place at the back of the queue (no args).
size_t size() const
Return the number of currently queued items.
bool recv(T &out)
Receive an item from the channel into out.
bool try_send(const T &value)
Attempt to send a value without blocking.
bool try_recv(T &out)
Attempt to receive an item into out without blocking.
void close()
Close the channel.
bool send(const T &value)
Send a value by copying it into the channel.
Cooperative cancellation source paired with CancellationToken.
Read-only cooperative cancellation token.
Read/write-lock protected shared object wrapper.
decltype(auto) with_read_lock(F &&f) const
Execute a callback with shared (read-only) access.
ReadLockedPtr read() const
Acquire a shared lock and return a guard.
WriteLockedPtr write()
Acquire an exclusive lock and return a guard.
decltype(auto) with_write_lock(F &&f)
Execute a callback with exclusive (write) access.
Bounded single-producer/single-consumer queue.
bool try_pop(T &out)
Attempt to pop an item from the queue into out.
bool empty() const noexcept
Check if the queue is empty.
bool full() const noexcept
Check if the queue is full.
bool try_push(const T &value)
Attempt to push an item (copy) into the queue.
Mutex-protected shared object wrapper.
decltype(auto) with_lock(F &&f)
Execute a callback with exclusive access to the value.
LockedPtr lock()
Acquire an exclusive lock and return a guard.
Minimal structured-concurrency helper over ThreadPool futures.
void launch(F &&f, Args &&... args)
Launch a task that belongs to this group.
A reusable thread pool for efficient parallel task execution.
Exception thrown when cooperative cancellation is observed.
Modern synchronization helpers for channels, shared state, and small producer-consumer queues.
#define TEST(name)
static mt19937 rng
Main namespace for Aleph-w library functions.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
STL namespace.
static long counter
Definition test-splice.C:40
static int * k
A modern, efficient thread pool for parallel task execution.