-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcs.cpp
92 lines (73 loc) · 1.71 KB
/
mcs.cpp
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
86
87
88
89
90
91
92
#include <atomic>
#include <thread>
#include <vector>
#include <set>
#include <iostream>
struct mlock {
std::atomic<mlock*> _next;
std::atomic_bool _locked;
mlock() : _next(nullptr), _locked(true) {}
void reset() {
_next.store(nullptr, std::memory_order_relaxed);
_locked.store(true, std::memory_order_relaxed);
}
};
class mcs_lock {
std::atomic<mlock*> _tail;
public:
mcs_lock() : _tail(nullptr) {}
void lock(mlock& m) {
mlock* old = _tail.exchange(&m);
if(old) {
m.reset();
old->_next.store(&m, std::memory_order_release);
while(m._locked.load(std::memory_order_acquire))
asm("pause");
}
}
void unlock(mlock& m) {
mlock* expected = &m;
if(!_tail.compare_exchange_strong(expected, nullptr)) {
while(!m._next.load(std::memory_order_acquire)) // next is a nullptr
asm("pause");
m._next.load(std::memory_order_relaxed)->_locked.store(false);
}
}
};
template<size_t TagNumber = 0>
class easy_mcs_lock : private mcs_lock {
static thread_local mlock m;
public:
void lock() {
mcs_lock::lock(m);
}
void unlock() {
mcs_lock::unlock(m);
}
};
template<size_t TagNumber>
thread_local mlock easy_mcs_lock<TagNumber>::m;
static easy_mcs_lock<> lock;
static std::set<int> nums;
void foo(const int i) {
lock.lock();
nums.insert(i);
lock.unlock();
lock.lock();
nums.erase(nums.find(i));
lock.unlock();
}
int main(int argc, char** argv) {
if(argc != 2)
return 2;
std::vector<std::thread> threads;
for(int i = 0; i < atoi(argv[1]); i++) {
threads.emplace_back(foo, i);
}
for(auto& t : threads)
t.join();
for(int i : nums)
std::cout << i << ',';
std::cout << std::endl;
return errno;
}