-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.h
More file actions
67 lines (58 loc) · 1.83 KB
/
solution.h
File metadata and controls
67 lines (58 loc) · 1.83 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
#include <atomic>
#include <thread>
template <typename T>
class LockFreeStack {
public:
LockFreeStack() {
}
~LockFreeStack() {
Node* current_head = head.load();
while (current_head != nullptr) {
Node* removable = current_head;
current_head = current_head->child.load();
delete removable;
}
current_head = trash_head.load();
while (current_head != nullptr) {
Node* removable = current_head;
current_head = current_head->child.load();
delete removable;
}
}
void Push(T element) {
Node* current_head = head.load();
Node* new_head = new Node(element);
new_head->child.store(current_head);
while (!head.compare_exchange_strong(current_head, new_head)) {
new_head->child.store(current_head);
}
}
bool Pop(T& element) {
Node* current_head = head.load();
while (current_head != nullptr) {
if (head.compare_exchange_strong(current_head, current_head->child.load())) {
element = current_head->element;
Node* current_trash_head = trash_head.load();
current_head->child.store(current_trash_head);
while (!trash_head.compare_exchange_strong(current_trash_head, current_head)) {
current_head->child.store(current_trash_head);
}
return true;
}
}
return false;
}
private:
struct Node {
T element;
std::atomic<Node*> child;
Node(T element) {
this->element = element;
this->child = nullptr;
}
};
std::atomic<Node*> head {nullptr};
std::atomic<Node*> trash_head {nullptr};
};
template <typename T>
using ConcurrentStack = LockFreeStack<T>;