Anklang-0.3.0.dev712+gdc4e642f anklang-0.3.0.dev712+gdc4e642f
ASE — Anklang Sound Engine (C++)

« « « Anklang Documentation
Loading...
Searching...
No Matches
system.cc
Go to the documentation of this file.
1 // This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
2#include <cstdio>
3#include <atomic>
4#include <thread>
5#include <chrono>
6#include <ase/platform.hh>
7#include "../testing.hh"
8
9namespace { // Anon
10
11// Test semaphore with multiple posts and waits
12static void
13semaphore_multiple_test()
14{
15 using namespace Ase;
17
18 // Post twice
19 sem.post();
20 sem.post();
21
22 // Two waits should succeed
23 TCHECK (sem.wait() == 0, "First sem.wait() should succeed");
24 TCHECK (sem.wait() == 0, "Second sem.wait() should succeed");
25
26 // Third wait should timeout (no more posts)
27 int ret = sem.wait_for (20000); // 20ms timeout
28 TCHECK (ret != 0, "Third sem.wait_for() should timeout");
29}
30TEST_ADD (semaphore_multiple_test);
31
32// Test semaphore with concurrent waiters (first waiter gets the post)
33static void
34semaphore_concurrent_test()
35{
36 using namespace Ase;
38
39 std::atomic<bool> waiter1_done {false};
40 std::atomic<bool> waiter2_done {false};
41 std::atomic<int> waiter1_ret {0};
42 std::atomic<int> waiter2_ret {0};
43
44 std::thread t1 ([&]() {
45 waiter1_ret = sem.wait_for (100000); // 100ms
46 waiter1_done = true;
47 });
48
49 std::thread t2 ([&]() {
50 waiter2_ret = sem.wait_for (100000); // 100ms
51 waiter2_done = true;
52 });
53
54 // Small delay to ensure both threads are waiting
56
57 // Post once - only one waiter should get it
58 sem.post();
59
60 t1.join();
61 t2.join();
62
63 // One waiter should succeed (ret == 0), the other should timeout
64 TCHECK (waiter1_done && waiter2_done, "Both waiters should complete");
65 TCHECK ((waiter1_ret == 0) != (waiter2_ret == 0), "Exactly one waiter should succeed");
66}
67TEST_ADD (semaphore_concurrent_test);
68
69} // Anon
int wait() noexcept
Wait indefinitely for ScopedSemaphore.
Definition platform.cc:873
int wait_for(uint64_t useconds) noexcept
Wait for ScopedSemaphore with timeout (microseconds).
Definition platform.cc:883
int post() noexcept
Unlock ScopedSemaphore.
Definition platform.cc:863
The Anklang C++ API namespace.
Definition api.hh:9
T sleep_for(T... args)
#define TEST_ADD(fun)
Register a function to run as part of the unit test suite.
Definition testing.hh:31
#define TCHECK(cond,...)
Verbose assertion, calls TPASS() on success./*#end#*‍/.
Definition testing.hh:19