Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/core/templates/safe_list.h
9973 views
1
/**************************************************************************/
2
/* safe_list.h */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#pragma once
32
33
#include "core/os/memory.h"
34
#include "core/typedefs.h"
35
36
#include <atomic>
37
#include <functional>
38
#include <initializer_list>
39
40
// Design goals for these classes:
41
// - Accessing this list with an iterator will never result in a use-after free,
42
// even if the element being accessed has been logically removed from the list on
43
// another thread.
44
// - Logical deletion from the list will not result in deallocation at that time,
45
// instead the node will be deallocated at a later time when it is safe to do so.
46
// - No blocking synchronization primitives will be used.
47
48
// This is used in very specific areas of the engine where it's critical that these guarantees are held.
49
50
template <typename T, typename A = DefaultAllocator>
51
class SafeList {
52
struct SafeListNode {
53
std::atomic<SafeListNode *> next = nullptr;
54
55
// If the node is logically deleted, this pointer will typically point
56
// to the previous list item in time that was also logically deleted.
57
std::atomic<SafeListNode *> graveyard_next = nullptr;
58
59
std::function<void(T)> deletion_fn = [](T t) { return; };
60
61
T val;
62
};
63
64
static_assert(std::atomic<T>::is_always_lock_free);
65
66
std::atomic<SafeListNode *> head = nullptr;
67
std::atomic<SafeListNode *> graveyard_head = nullptr;
68
69
std::atomic_uint active_iterator_count = 0;
70
71
public:
72
class Iterator {
73
friend class SafeList;
74
75
SafeListNode *cursor = nullptr;
76
SafeList *list = nullptr;
77
78
Iterator(SafeListNode *p_cursor, SafeList *p_list) :
79
cursor(p_cursor), list(p_list) {
80
list->active_iterator_count++;
81
}
82
83
public:
84
Iterator(const Iterator &p_other) :
85
cursor(p_other.cursor), list(p_other.list) {
86
list->active_iterator_count++;
87
}
88
89
~Iterator() {
90
list->active_iterator_count--;
91
}
92
93
public:
94
T &operator*() {
95
return cursor->val;
96
}
97
98
Iterator &operator++() {
99
cursor = cursor->next;
100
return *this;
101
}
102
103
// These two operators are mostly useful for comparisons to nullptr.
104
bool operator==(const void *p_other) const {
105
return cursor == p_other;
106
}
107
108
bool operator!=(const void *p_other) const {
109
return cursor != p_other;
110
}
111
112
// These two allow easy range-based for loops.
113
bool operator==(const Iterator &p_other) const {
114
return cursor == p_other.cursor;
115
}
116
117
bool operator!=(const Iterator &p_other) const {
118
return cursor != p_other.cursor;
119
}
120
};
121
122
public:
123
// Calling this will cause an allocation.
124
void insert(T p_value) {
125
SafeListNode *new_node = memnew_allocator(SafeListNode, A);
126
new_node->val = p_value;
127
SafeListNode *expected_head = nullptr;
128
do {
129
expected_head = head.load();
130
new_node->next.store(expected_head);
131
} while (!head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ new_node));
132
}
133
134
Iterator find(T p_value) {
135
for (Iterator it = begin(); it != end(); ++it) {
136
if (*it == p_value) {
137
return it;
138
}
139
}
140
return end();
141
}
142
143
void erase(T p_value, std::function<void(T)> p_deletion_fn) {
144
Iterator tmp = find(p_value);
145
erase(tmp, p_deletion_fn);
146
}
147
148
void erase(T p_value) {
149
Iterator tmp = find(p_value);
150
erase(tmp, [](T t) { return; });
151
}
152
153
void erase(Iterator &p_iterator, std::function<void(T)> p_deletion_fn) {
154
p_iterator.cursor->deletion_fn = p_deletion_fn;
155
erase(p_iterator);
156
}
157
158
void erase(Iterator &p_iterator) {
159
if (find(p_iterator.cursor->val) == nullptr) {
160
// Not in the list, nothing to do.
161
return;
162
}
163
// First, remove the node from the list.
164
while (true) {
165
Iterator prev = begin();
166
SafeListNode *expected_head = prev.cursor;
167
for (; prev != end(); ++prev) {
168
if (prev.cursor && prev.cursor->next == p_iterator.cursor) {
169
break;
170
}
171
}
172
if (prev != end()) {
173
// There exists a node before this.
174
prev.cursor->next.store(p_iterator.cursor->next.load());
175
// Done.
176
break;
177
} else {
178
if (head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ p_iterator.cursor->next.load())) {
179
// Successfully reassigned the head pointer before another thread changed it to something else.
180
break;
181
}
182
// Fall through upon failure, try again.
183
}
184
}
185
// Then queue it for deletion by putting it in the node graveyard.
186
// Don't touch `next` because an iterator might still be pointing at this node.
187
SafeListNode *expected_head = nullptr;
188
do {
189
expected_head = graveyard_head.load();
190
p_iterator.cursor->graveyard_next.store(expected_head);
191
} while (!graveyard_head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ p_iterator.cursor));
192
}
193
194
Iterator begin() {
195
return Iterator(head.load(), this);
196
}
197
198
Iterator end() {
199
return Iterator(nullptr, this);
200
}
201
202
// Calling this will cause zero to many deallocations.
203
bool maybe_cleanup() {
204
SafeListNode *cursor = nullptr;
205
SafeListNode *new_graveyard_head = nullptr;
206
do {
207
// The access order here is theoretically important.
208
cursor = graveyard_head.load();
209
if (active_iterator_count.load() != 0) {
210
// It's not safe to clean up with an active iterator, because that iterator
211
// could be pointing to an element that we want to delete.
212
return false;
213
}
214
// Any iterator created after this point will never point to a deleted node.
215
// Swap it out with the current graveyard head.
216
} while (!graveyard_head.compare_exchange_strong(/* expected= */ cursor, /* new= */ new_graveyard_head));
217
// Our graveyard list is now unreachable by any active iterators,
218
// detached from the main graveyard head and ready for deletion.
219
while (cursor) {
220
SafeListNode *tmp = cursor;
221
cursor = cursor->graveyard_next;
222
tmp->deletion_fn(tmp->val);
223
memdelete_allocator<SafeListNode, A>(tmp);
224
}
225
return true;
226
}
227
228
_FORCE_INLINE_ SafeList() {}
229
_FORCE_INLINE_ SafeList(std::initializer_list<T> p_init) {
230
for (const T &E : p_init) {
231
insert(E);
232
}
233
}
234
235
~SafeList() {
236
#ifdef DEBUG_ENABLED
237
if (!maybe_cleanup()) {
238
ERR_PRINT("There are still iterators around when destructing a SafeList. Memory will be leaked. This is a bug.");
239
}
240
#else
241
maybe_cleanup();
242
#endif
243
}
244
};
245
246