-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex05_concurrency_policy.cpp
More file actions
70 lines (59 loc) · 1.88 KB
/
ex05_concurrency_policy.cpp
File metadata and controls
70 lines (59 loc) · 1.88 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
/*
* Example: ex05_concurrency_policy
*
* Purpose:
* Demonstrate the fenced concurrency policy path under multi-threaded
* repeated dispatch.
*
* Expected results:
* - Concurrent add operations consistently produce value 42.
* - Primitive load/store/CAS APIs work under fenced policy.
* - mismatch_count remains zero after all worker threads join.
* - Program prints a success message and exits with code 0.
*/
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
import mcpplibs.primitives;
using namespace mcpplibs::primitives;
int main() {
// Point 5: Use fenced concurrency policy and verify concurrent consistency.
using fenced_t =
primitive<int, policy::value::checked, policy::concurrency::fenced,
policy::error::expected>;
auto const lhs = fenced_t{12};
auto const rhs = fenced_t{30};
auto concurrent_value = fenced_t{1};
concurrent_value.store(2);
auto expected = 2;
if (!concurrent_value.compare_exchange(expected, 3) ||
concurrent_value.load() != 3) {
std::cerr << "fenced load/store/CAS mismatch\n";
return 1;
}
std::atomic<int> mismatch_count{0};
std::vector<std::thread> workers;
workers.reserve(4);
// Run many concurrent dispatches. Any error or wrong value is counted.
for (int i = 0; i < 4; ++i) {
workers.emplace_back([&]() {
for (int n = 0; n < 10000; ++n) {
auto const out = operations::add(lhs, rhs);
if (!out.has_value() || out->value() != 42) {
mismatch_count.fetch_add(1, std::memory_order_relaxed);
}
}
});
}
for (auto &worker : workers) {
worker.join();
}
// A non-zero mismatch count indicates unexpected behavior under concurrency.
if (mismatch_count.load(std::memory_order_relaxed) != 0) {
std::cerr << "fenced policy path mismatch\n";
return 1;
}
std::cout << "concurrency_policy demo passed\n";
return 0;
}