1 /*------------------------------------------------------------------------
2 Junction: Concurrent data structures in C++
3 Copyright (c) 2016 Jeff Preshing
5 Distributed under the Simplified BSD License.
6 Original location: https://github.com/preshing/junction
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the LICENSE file for more information.
11 ------------------------------------------------------------------------*/
13 #ifndef JUNCTION_CONCURRENTMAP_LINEAR_H
14 #define JUNCTION_CONCURRENTMAP_LINEAR_H
16 #include <junction/Core.h>
17 #include <junction/details/Linear.h>
18 #include <junction/QSBR.h>
19 #include <turf/Heap.h>
20 #include <turf/Trace.h>
24 TURF_TRACE_DECLARE(ConcurrentMap_Linear, 18)
26 template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V>>
27 class ConcurrentMap_Linear {
32 typedef VT ValueTraits;
33 typedef typename turf::util::BestFit<Key>::Unsigned Hash;
34 typedef details::Linear<ConcurrentMap_Linear> Details;
37 turf::Atomic<typename Details::Table*> m_root;
40 ConcurrentMap_Linear(ureg capacity) {
41 ureg limitNumValues = capacity * 3 / 4;
42 m_root.storeNonatomic(Details::Table::create(capacity, limitNumValues));
45 ~ConcurrentMap_Linear() {
46 typename Details::Table* table = m_root.loadNonatomic();
50 // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
51 // after all the threads participating in the migration have completed their work.
52 void publishTableMigration(typename Details::TableMigration* migration) {
53 // There are no racing calls to this function.
54 typename Details::Table* oldRoot = m_root.loadNonatomic();
55 m_root.store(migration->m_destination, turf::Release);
56 TURF_ASSERT(oldRoot == migration->m_source);
57 // Caller will GC the TableMigration and the source table.
60 // A Mutator represents a known cell in the hash table.
61 // It's meant for manipulations within a temporary function scope.
62 // Obviously you must not call QSBR::Update while holding a Mutator.
63 // Any operation that modifies the table (exchangeValue, eraseValue)
64 // may be forced to follow a redirected cell, which changes the Mutator itself.
65 // Note that even if the Mutator was constructed from an existing cell,
66 // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
67 // or if another thread deletes the key between the two steps.
70 friend class ConcurrentMap_Linear;
72 ConcurrentMap_Linear& m_map;
73 typename Details::Table* m_table;
74 typename Details::Cell* m_cell;
77 // Constructor: Find existing cell
78 Mutator(ConcurrentMap_Linear& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
79 TURF_TRACE(ConcurrentMap_Linear, 0, "[Mutator] find constructor called", uptr(m_table), uptr(key));
80 Hash hash = KeyTraits::hash(key);
82 m_table = m_map.m_root.load(turf::Consume);
83 m_cell = Details::find(hash, m_table);
86 m_value = m_cell->value.load(turf::Consume);
87 if (m_value != Value(ValueTraits::Redirect))
88 return; // Found an existing value
89 // We've encountered a Redirect value. Help finish the migration.
90 TURF_TRACE(ConcurrentMap_Linear, 1, "[Mutator] find was redirected", uptr(m_table), uptr(0));
91 m_table->jobCoordinator.participate();
92 // Try again using the latest root.
96 // Constructor: Insert cell
97 Mutator(ConcurrentMap_Linear& map, Key key) : m_map(map), m_table(map.m_root.load(turf::Consume)), m_value(Value(ValueTraits::NullValue)) {
98 TURF_TRACE(ConcurrentMap_Linear, 2, "[Mutator] insert constructor called", uptr(m_table), uptr(key));
99 Hash hash = KeyTraits::hash(key);
101 m_table = m_map.m_root.load(turf::Consume);
102 switch (Details::insert(hash, m_table, m_cell)) { // Modifies m_cell
103 case Details::InsertResult_InsertedNew: {
104 // We've inserted a new cell. Don't load m_cell->value.
107 case Details::InsertResult_AlreadyFound: {
108 // The hash was already found in the table.
109 m_value = m_cell->value.load(turf::Consume);
110 if (m_value == Value(ValueTraits::Redirect)) {
111 // We've encountered a Redirect value.
112 TURF_TRACE(ConcurrentMap_Linear, 3, "[Mutator] insert was redirected", uptr(m_table), uptr(m_value));
113 break; // Help finish the migration.
115 return; // Found an existing value
117 case Details::InsertResult_Overflow: {
118 Details::beginTableMigration(m_map, m_table);
122 // A migration has been started (either by us, or another thread). Participate until it's complete.
123 m_table->jobCoordinator.participate();
124 // Try again using the latest root.
129 Value getValue() const {
130 // Return previously loaded value. Don't load it again.
131 return Value(m_value);
134 Value exchangeValue(Value desired) {
135 TURF_ASSERT(desired != Value(ValueTraits::NullValue));
136 TURF_ASSERT(m_cell); // Cell must have been found or inserted
137 TURF_TRACE(ConcurrentMap_Linear, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
139 Value oldValue = m_value;
140 s32 prevRemainingValues = s32(-1);
141 if (oldValue == Value(ValueTraits::NullValue)) {
142 // It's a deleted or newly initialized cell.
143 // Decrement remainingValues to ensure we have permission to (re)insert a value.
144 prevRemainingValues = m_table->valuesRemaining.fetchSub(1, turf::Relaxed);
145 if (prevRemainingValues <= 0) {
146 TURF_TRACE(ConcurrentMap_Linear, 5, "[Mutator::exchangeValue] ran out of valuesRemaining", uptr(m_table), prevRemainingValues);
147 // Can't (re)insert any more values.
148 // There are two ways this can happen. One with a TableMigration already in progress, and one without:
149 // 1. A TableMigration puts a cap on the number of values late-arriving threads are allowed to insert.
150 // 2. Two threads race to insert the same key, and it's the last free cell in the table.
151 // (Note: We could get tid of the valuesRemaining counter by handling the possibility of migration failure,
152 // as LeapFrog and Grampa do...)
153 m_table->valuesRemaining.fetchAdd(1, turf::Relaxed); // Undo valuesRemaining decrement
154 // Since we don't know whether there's already a TableMigration in progress, always attempt to start one here:
155 Details::beginTableMigration(m_map, m_table);
159 if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
160 // Exchange was successful. Return previous value.
161 TURF_TRACE(ConcurrentMap_Linear, 6, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
162 Value result = m_value;
163 m_value = desired; // Leave the mutator in a valid state
166 // The CAS failed and m_value has been updated with the latest value.
167 if (m_value != Value(ValueTraits::Redirect)) {
168 TURF_TRACE(ConcurrentMap_Linear, 7, "[Mutator::exchangeValue] detected race to write value", uptr(m_table), uptr(m_value));
169 if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
170 TURF_TRACE(ConcurrentMap_Linear, 8, "[Mutator::exchangeValue] racing write inserted new value", uptr(m_table), uptr(m_value));
171 m_table->valuesRemaining.fetchAdd(1, turf::Relaxed); // Undo valuesRemaining decrement
173 // There was a racing write (or erase) to this cell.
174 // Pretend we exchanged with ourselves, and just let the racing write win.
177 // We've encountered a Redirect value. Help finish the migration.
178 TURF_TRACE(ConcurrentMap_Linear, 9, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
180 // Help migrate to new table.
181 Hash hash = m_cell->hash.load(turf::Relaxed);
183 // Help complete the migration.
184 m_table->jobCoordinator.participate();
185 // Try again in the new table.
186 m_table = m_map.m_root.load(turf::Consume);
187 m_value = Value(ValueTraits::NullValue);
188 switch (Details::insert(hash, m_table, m_cell)) { // Modifies m_cell
189 case Details::InsertResult_AlreadyFound:
190 m_value = m_cell->value.load(turf::Consume);
191 if (m_value == Value(ValueTraits::Redirect)) {
192 TURF_TRACE(ConcurrentMap_Linear, 10, "[Mutator::exchangeValue] was re-redirected", uptr(m_table), uptr(m_value));
196 case Details::InsertResult_InsertedNew:
198 case Details::InsertResult_Overflow:
199 TURF_TRACE(ConcurrentMap_Linear, 11, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), 0);
200 Details::beginTableMigration(m_map, m_table);
203 // We were redirected... again
207 // Try again in the new table.
211 void setValue(Value desired) {
212 exchangeValue(desired);
216 TURF_ASSERT(m_cell); // Cell must have been found or inserted
217 TURF_TRACE(ConcurrentMap_Linear, 12, "[Mutator::eraseValue] called", uptr(m_table), m_cell - m_table->getCells());
219 if (m_value == Value(ValueTraits::NullValue))
220 return Value(m_value);
221 TURF_ASSERT(m_cell); // m_value is non-NullValue, therefore cell must have been found or inserted.
222 if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
223 // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
224 TURF_ASSERT(m_value != ValueTraits::NullValue); // Implied by the test at the start of the loop.
225 m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);
226 Value result = m_value;
227 m_value = Value(ValueTraits::NullValue); // Leave the mutator in a valid state
230 // The CAS failed and m_value has been updated with the latest value.
231 TURF_TRACE(ConcurrentMap_Linear, 13, "[Mutator::eraseValue] detected race to write value", uptr(m_table), m_cell - m_table->getCells());
232 if (m_value != Value(ValueTraits::Redirect)) {
233 // There was a racing write (or erase) to this cell.
234 // Pretend we erased nothing, and just let the racing write win.
235 return Value(ValueTraits::NullValue);
237 // We've been redirected to a new table.
238 TURF_TRACE(ConcurrentMap_Linear, 14, "[Mutator::eraseValue] was redirected", uptr(m_table), m_cell - m_table->getCells());
239 Hash hash = m_cell->hash.load(turf::Relaxed); // Re-fetch hash
241 // Help complete the migration.
242 m_table->jobCoordinator.participate();
243 // Try again in the new table.
244 m_table = m_map.m_root.load(turf::Consume);
245 m_cell = Details::find(hash, m_table);
247 m_value = Value(ValueTraits::NullValue);
250 m_value = m_cell->value.load(turf::Relaxed);
251 if (m_value != Value(ValueTraits::Redirect))
253 TURF_TRACE(ConcurrentMap_Linear, 15, "[Mutator::eraseValue] was re-redirected", uptr(m_table), m_cell - m_table->getCells());
259 Mutator insert(Key key) {
260 return Mutator(*this, key);
263 Mutator find(Key key) {
264 return Mutator(*this, key, false);
267 // Lookup without creating a temporary Mutator.
269 Hash hash = KeyTraits::hash(key);
270 TURF_TRACE(ConcurrentMap_Linear, 16, "[get] called", uptr(this), uptr(hash));
272 typename Details::Table* table = m_root.load(turf::Consume);
273 typename Details::Cell* cell = Details::find(hash, table);
275 return Value(ValueTraits::NullValue);
276 Value value = cell->value.load(turf::Consume);
277 if (value != Value(ValueTraits::Redirect))
278 return value; // Found an existing value
279 // We've been redirected to a new table. Help with the migration.
280 TURF_TRACE(ConcurrentMap_Linear, 17, "[get] was redirected", uptr(table), uptr(cell));
281 table->jobCoordinator.participate();
282 // Try again in the new table.
286 Value insert(Key key, Value desired) {
287 Mutator iter(*this, key);
288 return iter.exchangeValue(desired);
291 Value exchange(Key key, Value desired) {
292 Mutator iter(*this, key);
293 return iter.exchangeValue(desired);
296 Value erase(Key key) {
297 Mutator iter(*this, key, false);
298 return iter.eraseValue();
301 // The easiest way to implement an Iterator is to prevent all Redirects.
302 // The currrent Iterator does that by forbidding concurrent inserts.
303 // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
306 typename Details::Table* m_table;
312 Iterator(ConcurrentMap_Linear& map) {
313 // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
314 m_table = map.m_root.load(turf::Consume);
320 TURF_ASSERT(m_table);
321 TURF_ASSERT(isValid() || m_idx == -1); // Either the Iterator is already valid, or we've just started iterating.
322 while (++m_idx <= m_table->sizeMask) {
323 // Index still inside range of table.
324 typename Details::Cell *cell = m_table->getCells() + m_idx;
325 m_hash = cell->hash.load(turf::Relaxed);
326 if (m_hash != KeyTraits::NullHash) {
327 // Cell has been reserved.
328 m_value = cell->value.load(turf::Relaxed);
329 TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
330 if (m_value != Value(ValueTraits::NullValue))
331 return; // Yield this cell.
334 // That's the end of the map.
335 m_hash = KeyTraits::NullHash;
336 m_value = ValueTraits::NullValue;
339 bool isValid() const {
340 return m_value != Value(ValueTraits::NullValue);
344 TURF_ASSERT(isValid());
345 // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
346 return KeyTraits::dehash(m_hash);
349 Value getValue() const {
350 TURF_ASSERT(isValid());
356 } // namespace junction
358 #endif // JUNCTION_CONCURRENTMAP_LINEAR_H