-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcs.cpp
More file actions
60 lines (52 loc) · 1.42 KB
/
Copy pathmcs.cpp
File metadata and controls
60 lines (52 loc) · 1.42 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
#include <iostream>
#include <thread>
#include <atomic>
class LinkedListElem {
public:
std::atomic<int> flag;
LinkedListElem* next;
};
class MCS {
std::atomic<LinkedListElem*> tail;
public:
void acquire(LinkedListElem* e, int thread_id) {
LinkedListElem* pred = tail.exchange(e);
e->next = nullptr;
if (pred == nullptr) {
e->flag.store(0);
}
else {
pred->next = e;
e->flag.store(1);
while(e->flag.load() == 1) {
// *spin
}
}
std::cout << "Acquired: " << thread_id << std::endl;
}
void release(LinkedListElem* e, int thread_id) {
if(e->next == nullptr) {
while(!tail.compare_exchange_strong(e, NULL)) {
if(e->next != NULL) {
e->next->flag.store(0);
}
}
}
else {
e->next->flag.store(0);
}
std::cout << "Released: " << thread_id << std::endl;
}
};
void acquire_and_release(MCS* m, int thread_id) {
LinkedListElem e;
m->acquire(&e, thread_id);
m->release(&e, thread_id);
}
int main() {
MCS m;
std::thread t1(acquire_and_release, &m, 0);
std::thread t2(acquire_and_release, &m, 1);
t1.join();
t2.join();
}