forked from dtr-org/unit-e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcounting_semaphore_tests.cpp
More file actions
85 lines (65 loc) · 2 KB
/
Copy pathcounting_semaphore_tests.cpp
File metadata and controls
85 lines (65 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) 2018 The Unit-e developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <proposer/sync.h>
#include <test/test_unite.h>
#include <boost/test/unit_test.hpp>
#include <atomic>
#include <thread>
BOOST_AUTO_TEST_SUITE(semaphore_tests)
BOOST_AUTO_TEST_CASE(barrier_example) {
proposer::CountingSemaphore semaphore(0);
std::atomic<bool> t1_started(false);
std::atomic<bool> t2_started(false);
std::atomic<bool> t1_after_acquire(false);
std::atomic<bool> t2_after_acquire(false);
std::thread t1([&t1_started, &t1_after_acquire, &semaphore]() {
t1_started = true;
semaphore.acquire(3);
t1_after_acquire = true;
});
std::thread t2([&t2_started, &t2_after_acquire, &semaphore]() {
t2_started = true;
semaphore.acquire(2);
t2_after_acquire = true;
});
{
const time_t startedAt = std::time(nullptr);
while (!t1_started && !t2_started) {
// idle waiting - timeout after 30 seconds
assert(std::time(nullptr) - startedAt < 30);
std::this_thread::yield();
}
}
BOOST_CHECK(!t1_after_acquire);
BOOST_CHECK(!t2_after_acquire);
semaphore.release(2);
{
const time_t startedAt = std::time(nullptr);
while (!t2_after_acquire) {
// idle waiting - timeout after 30 seconds
assert(std::time(nullptr) - startedAt < 30);
std::this_thread::yield();
}
}
BOOST_CHECK(!t1_after_acquire);
BOOST_CHECK(t2_after_acquire);
semaphore.release(2);
std::this_thread::yield();
BOOST_CHECK(!t1_after_acquire);
BOOST_CHECK(t2_after_acquire);
semaphore.release(2);
{
const time_t startedAt = std::time(nullptr);
while (!t1_after_acquire) {
// idle waiting - timeout after 30 seconds
assert(std::time(nullptr) - startedAt < 30);
std::this_thread::yield();
}
}
BOOST_CHECK(t1_after_acquire);
BOOST_CHECK(t2_after_acquire);
t1.detach();
t2.detach();
}
BOOST_AUTO_TEST_SUITE_END()