Refactors test case
[junction.git] / junction / ConcurrentMap_Linear.h
1 /*------------------------------------------------------------------------
2   Junction: Concurrent data structures in C++
3   Copyright (c) 2016 Jeff Preshing
4
5   Distributed under the Simplified BSD License.
6   Original location: https://github.com/preshing/junction
7
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 ------------------------------------------------------------------------*/
12
13 #ifndef JUNCTION_CONCURRENTMAP_LINEAR_H
14 #define JUNCTION_CONCURRENTMAP_LINEAR_H
15
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>
21
22 namespace junction {
23
24 TURF_TRACE_DECLARE(ConcurrentMap_Linear, 17)
25
26 template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V> >
27 class ConcurrentMap_Linear {
28 public:
29     typedef K Key;
30     typedef V Value;
31     typedef KT KeyTraits;
32     typedef VT ValueTraits;
33     typedef typename turf::util::BestFit<Key>::Unsigned Hash;
34     typedef details::Linear<ConcurrentMap_Linear> Details;
35
36 private:
37     turf::Atomic<typename Details::Table*> m_root;
38
39 public:
40     ConcurrentMap_Linear(ureg capacity = Details::InitialSize) : m_root(Details::Table::create(capacity)) {
41     }
42
43     ~ConcurrentMap_Linear() {
44         typename Details::Table* table = m_root.loadNonatomic();
45         table->destroy();
46     }
47
48     // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
49     // after all the threads participating in the migration have completed their work.
50     void publishTableMigration(typename Details::TableMigration* migration) {
51         // There are no racing calls to this function.
52         typename Details::Table* oldRoot = m_root.loadNonatomic();
53         m_root.store(migration->m_destination, turf::Release);
54         TURF_ASSERT(oldRoot == migration->getSources()[0].table);
55         // Caller will GC the TableMigration and the source table.
56     }
57
58     // A Mutator represents a known cell in the hash table.
59     // It's meant for manipulations within a temporary function scope.
60     // Obviously you must not call QSBR::Update while holding a Mutator.
61     // Any operation that modifies the table (exchangeValue, eraseValue)
62     // may be forced to follow a redirected cell, which changes the Mutator itself.
63     // Note that even if the Mutator was constructed from an existing cell,
64     // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
65     // or if another thread deletes the key between the two steps.
66     class Mutator {
67     private:
68         friend class ConcurrentMap_Linear;
69
70         ConcurrentMap_Linear& m_map;
71         typename Details::Table* m_table;
72         typename Details::Cell* m_cell;
73         Value m_value;
74
75         // Constructor: Find existing cell
76         Mutator(ConcurrentMap_Linear& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
77             TURF_TRACE(ConcurrentMap_Linear, 0, "[Mutator] find constructor called", uptr(0), uptr(key));
78             Hash hash = KeyTraits::hash(key);
79             for (;;) {
80                 m_table = m_map.m_root.load(turf::Consume);
81                 m_cell = Details::find(hash, m_table);
82                 if (!m_cell)
83                     return;
84                 Value value = m_cell->value.load(turf::Consume);
85                 if (value != Value(ValueTraits::Redirect)) {
86                     // Found an existing value
87                     m_value = value;
88                     return;
89                 }
90                 // We've encountered a Redirect value. Help finish the migration.
91                 TURF_TRACE(ConcurrentMap_Linear, 1, "[Mutator] find was redirected", uptr(m_table), 0);
92                 m_table->jobCoordinator.participate();
93                 // Try again using the latest root.
94             }
95         }
96
97         // Constructor: Insert cell
98         Mutator(ConcurrentMap_Linear& map, Key key) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
99             TURF_TRACE(ConcurrentMap_Linear, 2, "[Mutator] insertOrFind constructor called", uptr(0), uptr(key));
100             Hash hash = KeyTraits::hash(key);
101             bool mustDouble = false;
102             for (;;) {
103                 m_table = m_map.m_root.load(turf::Consume);
104                 switch (Details::insertOrFind(hash, m_table, m_cell)) { // Modifies m_cell
105                 case Details::InsertResult_InsertedNew: {
106                     // We've inserted a new cell. Don't load m_cell->value.
107                     return;
108                 }
109                 case Details::InsertResult_AlreadyFound: {
110                     // The hash was already found in the table.
111                     Value value = m_cell->value.load(turf::Consume);
112                     if (value == Value(ValueTraits::Redirect)) {
113                         // We've encountered a Redirect value.
114                         TURF_TRACE(ConcurrentMap_Linear, 3, "[Mutator] insertOrFind was redirected", uptr(m_table), uptr(m_value));
115                         break; // Help finish the migration.
116                     }
117                     // Found an existing value
118                     m_value = value;
119                     return;
120                 }
121                 case Details::InsertResult_Overflow: {
122                     Details::beginTableMigration(m_map, m_table, mustDouble);
123                     break;
124                 }
125                 }
126                 // A migration has been started (either by us, or another thread). Participate until it's complete.
127                 m_table->jobCoordinator.participate();
128                 // If we still overflow after this, avoid an infinite loop by forcing the next table to double.
129                 mustDouble = true;
130                 // Try again using the latest root.
131             }
132         }
133
134     public:
135         Value getValue() const {
136             // Return previously loaded value. Don't load it again.
137             return Value(m_value);
138         }
139
140         Value exchangeValue(Value desired) {
141             TURF_ASSERT(desired != Value(ValueTraits::NullValue));
142             TURF_ASSERT(desired != Value(ValueTraits::Redirect));
143             TURF_ASSERT(m_cell); // Cell must have been found or inserted
144             TURF_TRACE(ConcurrentMap_Linear, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
145             bool mustDouble = false;
146             for (;;) {
147                 Value oldValue = m_value;
148                 if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
149                     // Exchange was successful. Return previous value.
150                     TURF_TRACE(ConcurrentMap_Linear, 5, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
151                     Value result = m_value;
152                     m_value = desired; // Leave the mutator in a valid state
153                     return result;
154                 }
155                 // The CAS failed and m_value has been updated with the latest value.
156                 if (m_value != Value(ValueTraits::Redirect)) {
157                     TURF_TRACE(ConcurrentMap_Linear, 6, "[Mutator::exchangeValue] detected race to write value", uptr(m_table),
158                                uptr(m_value));
159                     if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
160                         TURF_TRACE(ConcurrentMap_Linear, 7, "[Mutator::exchangeValue] racing write inserted new value",
161                                    uptr(m_table), uptr(m_value));
162                     }
163                     // There was a racing write (or erase) to this cell.
164                     // Pretend we exchanged with ourselves, and just let the racing write win.
165                     return desired;
166                 }
167                 // We've encountered a Redirect value. Help finish the migration.
168                 TURF_TRACE(ConcurrentMap_Linear, 8, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
169                 Hash hash = m_cell->hash.load(turf::Relaxed);
170                 for (;;) {
171                     // Help complete the migration.
172                     m_table->jobCoordinator.participate();
173                     // Try again in the new table.
174                     m_table = m_map.m_root.load(turf::Consume);
175                     m_value = Value(ValueTraits::NullValue);
176                     switch (Details::insertOrFind(hash, m_table, m_cell)) { // Modifies m_cell
177                     case Details::InsertResult_AlreadyFound:
178                         m_value = m_cell->value.load(turf::Consume);
179                         if (m_value == Value(ValueTraits::Redirect)) {
180                             TURF_TRACE(ConcurrentMap_Linear, 9, "[Mutator::exchangeValue] was re-redirected", uptr(m_table),
181                                        uptr(m_value));
182                             break;
183                         }
184                         goto breakOuter;
185                     case Details::InsertResult_InsertedNew:
186                         goto breakOuter;
187                     case Details::InsertResult_Overflow:
188                         TURF_TRACE(ConcurrentMap_Linear, 10, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), 0);
189                         Details::beginTableMigration(m_map, m_table, mustDouble);
190                         break;
191                     }
192                     // If we still overflow after this, avoid an infinite loop by forcing the next table to double.
193                     mustDouble = true;
194                     // We were redirected... again
195                 }
196             breakOuter:;
197                 // Try again in the new table.
198             }
199         }
200
201         void assignValue(Value desired) {
202             exchangeValue(desired);
203         }
204
205         Value eraseValue() {
206             TURF_ASSERT(m_cell); // Cell must have been found or inserted
207             TURF_TRACE(ConcurrentMap_Linear, 11, "[Mutator::eraseValue] called", uptr(m_table), m_cell - m_table->getCells());
208             for (;;) {
209                 if (m_value == Value(ValueTraits::NullValue))
210                     return Value(m_value);
211                 TURF_ASSERT(m_cell); // m_value is non-NullValue, therefore cell must have been found or inserted.
212                 if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
213                     // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
214                     TURF_ASSERT(m_value != ValueTraits::NullValue); // Implied by the test at the start of the loop.
215                     Value result = m_value;
216                     m_value = Value(ValueTraits::NullValue); // Leave the mutator in a valid state
217                     return result;
218                 }
219                 // The CAS failed and m_value has been updated with the latest value.
220                 TURF_TRACE(ConcurrentMap_Linear, 12, "[Mutator::eraseValue] detected race to write value", uptr(m_table),
221                            m_cell - m_table->getCells());
222                 if (m_value != Value(ValueTraits::Redirect)) {
223                     // There was a racing write (or erase) to this cell.
224                     // Pretend we erased nothing, and just let the racing write win.
225                     return Value(ValueTraits::NullValue);
226                 }
227                 // We've been redirected to a new table.
228                 TURF_TRACE(ConcurrentMap_Linear, 13, "[Mutator::eraseValue] was redirected", uptr(m_table),
229                            m_cell - m_table->getCells());
230                 Hash hash = m_cell->hash.load(turf::Relaxed); // Re-fetch hash
231                 for (;;) {
232                     // Help complete the migration.
233                     m_table->jobCoordinator.participate();
234                     // Try again in the new table.
235                     m_table = m_map.m_root.load(turf::Consume);
236                     m_cell = Details::find(hash, m_table);
237                     if (!m_cell) {
238                         m_value = Value(ValueTraits::NullValue);
239                         return m_value;
240                     }
241                     m_value = m_cell->value.load(turf::Relaxed);
242                     if (m_value != Value(ValueTraits::Redirect))
243                         break;
244                     TURF_TRACE(ConcurrentMap_Linear, 14, "[Mutator::eraseValue] was re-redirected", uptr(m_table),
245                                m_cell - m_table->getCells());
246                 }
247             }
248         }
249     };
250
251     Mutator insertOrFind(Key key) {
252         return Mutator(*this, key);
253     }
254
255     Mutator find(Key key) {
256         return Mutator(*this, key, false);
257     }
258
259     // Lookup without creating a temporary Mutator.
260     Value get(Key key) {
261         Hash hash = KeyTraits::hash(key);
262         TURF_TRACE(ConcurrentMap_Linear, 15, "[get] called", uptr(this), uptr(hash));
263         for (;;) {
264             typename Details::Table* table = m_root.load(turf::Consume);
265             typename Details::Cell* cell = Details::find(hash, table);
266             if (!cell)
267                 return Value(ValueTraits::NullValue);
268             Value value = cell->value.load(turf::Consume);
269             if (value != Value(ValueTraits::Redirect))
270                 return value; // Found an existing value
271             // We've been redirected to a new table. Help with the migration.
272             TURF_TRACE(ConcurrentMap_Linear, 16, "[get] was redirected", uptr(table), uptr(cell));
273             table->jobCoordinator.participate();
274             // Try again in the new table.
275         }
276     }
277
278     Value assign(Key key, Value desired) {
279         Mutator iter(*this, key);
280         return iter.exchangeValue(desired);
281     }
282
283     Value exchange(Key key, Value desired) {
284         Mutator iter(*this, key);
285         return iter.exchangeValue(desired);
286     }
287
288     Value erase(Key key) {
289         Mutator iter(*this, key, false);
290         return iter.eraseValue();
291     }
292
293     // The easiest way to implement an Iterator is to prevent all Redirects.
294     // The currrent Iterator does that by forbidding concurrent inserts.
295     // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
296     class Iterator {
297     private:
298         typename Details::Table* m_table;
299         ureg m_idx;
300         Key m_hash;
301         Value m_value;
302
303     public:
304         Iterator(ConcurrentMap_Linear& map) {
305             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
306             m_table = map.m_root.load(turf::Consume);
307             m_idx = -1;
308             next();
309         }
310
311         void next() {
312             TURF_ASSERT(m_table);
313             TURF_ASSERT(isValid() || m_idx == -1); // Either the Iterator is already valid, or we've just started iterating.
314             while (++m_idx <= m_table->sizeMask) {
315                 // Index still inside range of table.
316                 typename Details::Cell* cell = m_table->getCells() + m_idx;
317                 m_hash = cell->hash.load(turf::Relaxed);
318                 if (m_hash != KeyTraits::NullHash) {
319                     // Cell has been reserved.
320                     m_value = cell->value.load(turf::Relaxed);
321                     TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
322                     if (m_value != Value(ValueTraits::NullValue))
323                         return; // Yield this cell.
324                 }
325             }
326             // That's the end of the map.
327             m_hash = KeyTraits::NullHash;
328             m_value = Value(ValueTraits::NullValue);
329         }
330
331         bool isValid() const {
332             return m_value != Value(ValueTraits::NullValue);
333         }
334
335         Key getKey() const {
336             TURF_ASSERT(isValid());
337             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
338             return KeyTraits::dehash(m_hash);
339         }
340
341         Value getValue() const {
342             TURF_ASSERT(isValid());
343             return m_value;
344         }
345     };
346 };
347
348 } // namespace junction
349
350 #endif // JUNCTION_CONCURRENTMAP_LINEAR_H