-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_ms_queue.h
110 lines (92 loc) · 2.7 KB
/
simple_ms_queue.h
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// Created by konstantin on 01.07.24.
//
#pragma once
#include <atomic>
#include <optional>
#include <components/lock_free/hazard/hazard_manager.h>
#include <components/lock_free/hazard/mutator.h>
#include <components/lock_free/hazard/thread_state.h>
namespace NComponents {
/**
* Michael-Scott Queue
*
* dummy -> node1 -> node2
* head -> dummy
* tail -> node2
*
* ref:
* https://www.cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf
* https://cs.brown.edu/~mph/HerlihyW90/p463-herlihy.pdf
* https://www.1024cores.net/home/lock-free-algorithms/eventcounts
*
*/
template <class T>
class SimpleMSQueue final {
struct Node {
std::optional<T> value;
std::atomic<Node*> next{nullptr};
};
private:
std::atomic<Node*> head;
std::atomic<Node*> tail;
public:
SimpleMSQueue() {
Node* dummy = new Node{};
head.store(dummy);
tail.store(dummy);
}
~SimpleMSQueue() {
while (head != nullptr) {
Node* to_delete = head.load();
head.store(to_delete->next);
delete to_delete;
}
}
void Push(T item) {
Node* new_node = new Node{std::move(item), nullptr};
Node* old_tail{};
while (true) {
old_tail = tail.load();
if (old_tail->next.load() != nullptr) {
// concurrent push
// helping
tail.compare_exchange_weak(old_tail, old_tail->next);
continue;
}
Node* null_ptr = nullptr;
if (old_tail->next.compare_exchange_weak(null_ptr, new_node)) {
break;
}
}
tail.compare_exchange_strong(old_tail, new_node);
}
std::optional<T> TryPop(NHazard::Mutator& mutator) {
// auto mutator = NHazard::HazardManager::Get()->MakeMutator();
while (true) {
Node* old_head = mutator.Acquire(&head);
if (old_head->next.load() == nullptr) {
mutator.Release();
return {};
}
Node* old_tail = tail.load();
if (old_head == old_tail) {
// helping
tail.compare_exchange_weak(old_tail, old_tail->next);
continue;
}
if (head.compare_exchange_weak(old_head, old_head->next)) {
Node* next = old_head->next;
T result = std::move(*next->value);
mutator.Release();
mutator.Retire(old_head);
return result;
}
}
}
std::optional<T> TryPop() {
auto mutator = NHazard::HazardManager::Get()->MakeMutator();
return TryPop(mutator);
}
};
} // namespace NComponents