31#include <gtest/gtest.h>
49using namespace std::chrono_literals;
53 template <
typename Sync>
57 sync.with_lock([](
auto &
value) {
return value; });
60 template <
typename Sync>
64 sync.with_read_lock([](
const auto &
value) {
return value; });
67 template <
typename Sync>
71 sync.with_write_lock([](
auto &
value) {
return value; });
80 : token(
std::move(token_arg)),
value(value_arg) {}
83 struct ExceptionSafePayload
85 static inline bool throw_on_move_construction =
false;
86 static inline bool throw_on_move_assignment =
false;
90 ExceptionSafePayload() =
default;
92 explicit ExceptionSafePayload(
int value_arg)
95 ExceptionSafePayload(
const ExceptionSafePayload &) =
default;
96 ExceptionSafePayload & operator = (
const ExceptionSafePayload &) =
default;
98 ExceptionSafePayload(ExceptionSafePayload && other)
102 if (throw_on_move_construction)
103 throw std::runtime_error(
"move construction failed");
106 ExceptionSafePayload & operator = (ExceptionSafePayload && other)
110 if (throw_on_move_assignment)
111 throw std::runtime_error(
"move assignment failed");
115 static void reset_failures() noexcept
117 throw_on_move_construction =
false;
118 throw_on_move_assignment =
false;
123static_assert(SupportsValueReturningWithLock<synchronized<int>>);
124static_assert(SupportsValueReturningWithReadLock<rw_synchronized<int>>);
125static_assert(SupportsValueReturningWithWriteLock<rw_synchronized<int>>);
127TEST(ConcurrencyUtils, BoundedChannelCloseDrainsQueuedItems)
131 ASSERT_TRUE(ch.
send(10));
132 ASSERT_TRUE(ch.
send(20));
135 auto first = ch.
recv();
136 auto second = ch.
recv();
137 auto third = ch.
recv();
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));
147TEST(ConcurrencyUtils, BoundedChannelTrySendAndTryRecv)
157 ASSERT_TRUE(first.has_value());
158 EXPECT_EQ(*first, 7);
159 EXPECT_FALSE(second.has_value());
162TEST(ConcurrencyUtils, BoundedChannelCloseUnblocksSenderAndReceiver)
165 ASSERT_TRUE(full_ch.
send(1));
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));
175 while (not sender_entered.load(std::memory_order_acquire))
176 std::this_thread::yield();
178 EXPECT_FALSE(sender_future.get());
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());
190 while (not receiver_entered.load(std::memory_order_acquire))
191 std::this_thread::yield();
193 EXPECT_FALSE(receiver_future.get().has_value());
197TEST(ConcurrencyUtils, BoundedChannelProducerConsumerPreservesOrder)
200 std::vector<int> received;
201 received.reserve(2000);
202 std::atomic<bool> producer_ok{
true};
204 std::thread producer([&] {
205 for (
int i = 0; i < 2000; ++i)
207 producer_ok.store(
false, std::memory_order_relaxed);
211 std::thread consumer([&] {
212 while (
auto item = ch.
recv())
213 received.push_back(*item);
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));
225TEST(ConcurrencyUtils, BoundedChannelSupportsMoveOnlyPayloads)
229 ASSERT_TRUE(ch.
send(std::make_unique<int>(42)));
230 auto item = ch.
recv();
232 ASSERT_TRUE(item.has_value());
233 ASSERT_TRUE(item->get() !=
nullptr);
234 EXPECT_EQ(**item, 42);
237TEST(ConcurrencyUtils, BoundedChannelCancellationInterruptsBlockedSend)
241 ASSERT_TRUE(ch.
send(1));
243 std::atomic<bool> started{
false};
244 std::promise<bool> canceled;
245 auto future = canceled.get_future();
247 std::thread sender([&] {
248 started.store(
true, std::memory_order_release);
251 (void) ch.
send(2, source.token());
252 canceled.set_value(
false);
256 canceled.set_value(
true);
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();
265 EXPECT_TRUE(future.get());
269TEST(ConcurrencyUtils, BoundedChannelCancellationInterruptsBlockedRecv)
274 std::atomic<bool> started{
false};
275 std::promise<bool> canceled;
276 auto future = canceled.get_future();
278 std::thread receiver([&] {
279 started.store(
true, std::memory_order_release);
282 (void) ch.
recv(source.token());
283 canceled.set_value(
false);
287 canceled.set_value(
true);
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();
296 EXPECT_TRUE(future.get());
306TEST(ConcurrencyUtils, BoundedChannelNeverMissesTheCancellation)
308 std::mt19937
rng(20261015);
309 std::atomic<unsigned> sink{0};
310 for (
int round = 0; round < 5000; ++round)
313 const bool sending = round % 2 == 1;
315 ASSERT_TRUE(ch.
send(0));
318 std::atomic<bool> started{
false};
319 std::promise<void> done;
320 auto finished = done.get_future();
321 std::thread blocked([&] {
326 (
void) ch.
send(1, source.token());
328 (
void) ch.
recv(source.token());
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();
343 const bool seen = finished.wait_for(10s) == std::future_status::ready;
347 ASSERT_TRUE(seen) <<
"round " << round <<
" missed the cancellation";
353TEST(ConcurrencyUtils, BoundedChannelCanceledTokenThrowsInsteadOfWaiting)
357 source.request_cancel();
358 const auto token = source.token();
363 EXPECT_TRUE(ch.
send(1, token));
366 EXPECT_EQ(ch.
size(), 1u);
367 EXPECT_TRUE(ch.
recv(
out, token));
371TEST(ConcurrencyUtils, BoundedChannelCloseWinsIfOperationCanProceed)
376 ASSERT_TRUE(ch.
send(11));
378 source.request_cancel();
380 auto first = ch.
recv(source.token());
381 auto second = ch.
recv(source.token());
383 ASSERT_TRUE(first.has_value());
384 EXPECT_EQ(*first, 11);
385 EXPECT_FALSE(second.has_value());
388TEST(ConcurrencyUtils, BoundedChannelCancellationAppliesToEmplace)
392 ASSERT_TRUE(ch.
send(1));
394 std::atomic<bool> started{
false};
395 std::promise<bool> canceled;
396 auto future = canceled.get_future();
398 std::thread producer([&] {
399 started.store(
true, std::memory_order_release);
402 (void) ch.
emplace(source.token(), 2);
403 canceled.set_value(
false);
407 canceled.set_value(
true);
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();
416 EXPECT_TRUE(future.get());
420TEST(ConcurrencyUtils, BoundedChannelEmplaceAcceptsCancellationTokenPayloads)
424 auto token = source.token();
426 ASSERT_TRUE(ch.
emplace(token, 42));
428 auto received = ch.
recv();
429 ASSERT_TRUE(received.has_value());
430 EXPECT_EQ(received->value, 42);
431 EXPECT_FALSE(received->token.stop_requested());
433 source.request_cancel();
435 EXPECT_TRUE(received->token.stop_requested());
438TEST(ConcurrencyUtils, BoundedChannelRecvUsesCopyFallbackForThrowingMoves)
440 ExceptionSafePayload::reset_failures();
443 ASSERT_TRUE(ch.
send(ExceptionSafePayload(23)));
445 ExceptionSafePayload::throw_on_move_construction =
true;
446 auto received = ch.
recv();
447 ExceptionSafePayload::reset_failures();
449 ASSERT_TRUE(received.has_value());
450 EXPECT_EQ(received->value, 23);
453TEST(ConcurrencyUtils, BoundedChannelTryRecvPreservesQueuedValueOnAssignmentFailure)
455 ExceptionSafePayload::reset_failures();
458 ASSERT_TRUE(ch.
send(ExceptionSafePayload(17)));
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();
465 auto recovered = ch.
recv();
466 ASSERT_TRUE(recovered.has_value());
467 EXPECT_EQ(recovered->value, 17);
474TEST(ConcurrencyUtils, DefaultValueIsValueInitialized)
478 std::memset(buf, 0x5a,
sizeof(buf));
480 EXPECT_EQ(p->with_lock([] (
const long & v) { return v; }), 0);
481 p->~Synchronized<
long>();
485 std::memset(buf, 0x5a,
sizeof(buf));
487 EXPECT_EQ(p->with_read_lock([] (
const long & v) { return v; }), 0);
488 p->~RwSynchronized<
long>();
491 EXPECT_EQ(q.
with_lock([] (
double *
const & v) { return v; }),
nullptr);
494TEST(ConcurrencyUtils, SynchronizedWithLockAndGuard)
504 auto locked = values.
lock();
505 locked->push_back(3);
512 EXPECT_EQ(
copy, (std::vector<int>{1, 2, 3}));
515TEST(ConcurrencyUtils, SynchronizedCounterUnderContention)
521 for (
int worker = 0; worker < 8; ++worker)
523 for (int i = 0; i < 2000; ++i)
524 counter.with_lock([](int & value) { ++value; });
529 EXPECT_EQ(
counter.with_lock([](
const int &
value) { return value; }), 16000);
532TEST(ConcurrencyUtils, RwSynchronizedSupportsReadAndWriteAccess)
542 auto write_locked = values.
write();
543 write_locked->push_back(6);
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);
554 return std::accumulate(v.begin(), v.end(), 0);
558TEST(ConcurrencyUtils, SynchronizedSupportsNonDefaultConstructibleValues)
562 explicit Payload(
int x) :
value(x) {}
567 payload.
with_lock([](Payload & p) { p.value += 5; });
568 EXPECT_EQ(payload.
with_lock([](
const Payload & p) { return p.value; }), 12);
571TEST(ConcurrencyUtils, RwSynchronizedSupportsNonDefaultConstructibleValues)
575 explicit Payload(
int x) :
value(x) {}
581 EXPECT_EQ(payload.
with_read_lock([](
const Payload & p) { return p.value; }), 18);
584TEST(ConcurrencyUtils, SpscQueueBasicPushPop)
592 EXPECT_TRUE(queue.
full());
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());
609TEST(ConcurrencyUtils, SpscQueueProducerConsumerRoundTrip)
612 std::vector<int> received;
613 received.reserve(5000);
615 std::thread producer([&] {
616 for (
int i = 0; i < 5000; ++i)
618 std::this_thread::yield();
621 std::thread consumer([&] {
622 while (received.size() < 5000)
624 auto item = queue.try_pop();
625 if (item.has_value())
626 received.push_back(*item);
628 std::this_thread::yield();
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));
640TEST(ConcurrencyUtils, SpscQueueSupportsMoveOnlyValues)
644 ASSERT_TRUE(queue.
try_push(std::make_unique<int>(42)));
647 ASSERT_TRUE(item.has_value());
648 ASSERT_TRUE(item->get() !=
nullptr);
649 EXPECT_EQ(**item, 42);
652TEST(ConcurrencyUtils, SpscQueueTryPopUsesCopyFallbackForThrowingMoves)
654 ExceptionSafePayload::reset_failures();
657 ASSERT_TRUE(queue.
try_push(ExceptionSafePayload(31)));
659 ExceptionSafePayload::throw_on_move_construction =
true;
661 ExceptionSafePayload::reset_failures();
663 ASSERT_TRUE(item.has_value());
664 EXPECT_EQ(item->value, 31);
size_t size_t int32_t value
size_t size_t int32_t * out
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.
Main namespace for Aleph-w library functions.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
A modern, efficient thread pool for parallel task execution.