forked from facebook/redex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConcurrentContainers.h
2222 lines (1980 loc) · 71 KB
/
ConcurrentContainers.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <boost/intrusive/pointer_plus_bits.hpp>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <memory>
#include <mutex>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include "Debug.h"
#include "Timer.h"
namespace cc_impl {
constexpr size_t kDefaultSlots = 83;
template <typename Container, size_t n_slots>
class ConcurrentContainerIterator;
inline AccumulatingTimer s_destructor("cc_impl::destructor_seconds");
inline AccumulatingTimer s_reserving("cc_impl::reserving_seconds");
inline size_t s_concurrent_destruction_threshold{
std::numeric_limits<size_t>::max()};
bool is_thread_pool_active();
void workqueue_run_for(size_t start,
size_t end,
const std::function<void(size_t)>& fn);
template <typename ConcurrentHashtable>
class ConcurrentHashtableIterator;
template <typename ConcurrentHashtable>
class ConcurrentHashtableInsertionResult;
size_t get_prime_number_greater_or_equal_to(size_t);
/*
* This ConcurrentHashtable supports inserting (and "emplacing"), getting (the
* address of inserted key-value pairs), and erasing key-value pairs. There is
* no built-in support for mutation of previously inserted elements; however,
* once inserted, a key-value is assigned a fixed storage location that will
* remain valid until the concurrent hashtable is destroyed, or a destructive
* NOT thread-safe function such as `compact` is called.
*
* Some guiding principles for concurrency are:
* - All insertions/erasures performed on the current thread are reflected when
* calling get on the current thread.
* - Insertions/erasures performed by other threads will become visible
* eventually, but with no ordering guarantees.
*
* The concurrent hashtable has the following performance characteristics:
* - getting, inserting and erasing is O(1) on average, lock-free (*), and not
* blocked by resizing
* - resizing is O(n) on the current thread, and acquires a table-wide mutex
*
* (*) While implemented without locks, there is effectively some spinning on
* individual buckets when competing operations are in progress on that bucket.
*
* Resizing is automatically triggered when an insertion causes the table to
* exceed the (hard-coded) load factor, and then this insertion blocks the
* current thread while it is busy resizing. However, concurrent gets,
* insertions and erasures can proceed; new insertions will go into the enlarged
* table version, possibly (temporarily) exceeding the load factor.
*
* All key-value pairs are stored in a fixed memory location, and are not moved
* during resizing, similar to how std::unordered_set/map manages memory.
* Erasing a key does not immediately destroy the key-value pair, but keeps (a
* reference to) it until the concurrent hashtable is destroyed, copied, moved,
* or `compact` is called. This ensures that get always returns a valid
* reference, even in the face of concurrent erasing.
*
* TODO: Right now, we use the (default) std::memory_order_seq_cst everywhere.
* Acquire/release semantics should be sufficient.
*/
template <typename Key, typename Value, typename Hash, typename KeyEqual>
class ConcurrentHashtable final {
public:
using key_type = Key;
using value_type = Value;
using pointer = Value*;
using const_pointer = const Value*;
using reference = Value&;
using const_reference = const Value&;
using iterator = ConcurrentHashtableIterator<
ConcurrentHashtable<Key, Value, Hash, KeyEqual>>;
using const_iterator = ConcurrentHashtableIterator<
const ConcurrentHashtable<Key, Value, Hash, KeyEqual>>;
using hasher = Hash;
using key_equal = KeyEqual;
using insertion_result = ConcurrentHashtableInsertionResult<
ConcurrentHashtable<Key, Value, Hash, KeyEqual>>;
struct const_key_projection {
template <typename key_type2 = key_type,
typename = typename std::enable_if_t<
std::is_same_v<key_type2, value_type>>>
const key_type2& operator()(const key_type2& key) {
return key;
}
template <typename key_type2 = key_type,
typename = typename std::enable_if_t<
!std::is_same_v<key_type2, value_type>>>
const key_type2& operator()(const value_type& key) {
return key.first;
}
};
/*
* This operation by itself is always thread-safe. However, any mutating
* operations (concurrent or synchronous) invalidate all iterators.
*/
iterator begin() {
auto* storage = m_storage.load();
auto* ptr = storage->ptrs[0].load();
return iterator(storage, 0, get_node(ptr));
}
/*
* This operation by itself is always thread-safe. However, any mutating
* operations (concurrent or synchronous) invalidate all iterators.
*/
iterator end() {
auto* storage = m_storage.load();
return iterator(storage, storage->size, nullptr);
}
/*
* This operation by itself is always thread-safe. However, any mutating
* operations (concurrent or synchronous) invalidate all iterators.
*/
const_iterator begin() const {
auto* storage = m_storage.load();
auto* ptr = storage->ptrs[0].load();
return const_iterator(storage, 0, get_node(ptr));
}
/*
* This operation by itself is always thread-safe. However, any mutating
* operations (concurrent or synchronous) invalidate all iterators.
*/
const_iterator end() const {
auto* storage = m_storage.load();
return const_iterator(storage, storage->size, nullptr);
}
/*
* This operation by itself is always thread-safe. However, any mutating
* operations (concurrent or synchronous) invalidate all iterators.
*/
iterator find(const key_type& key) {
auto hash = hasher()(key);
auto* storage = m_storage.load();
auto* ptrs = storage->ptrs;
size_t i = hash % storage->size;
auto* root_loc = &ptrs[i];
auto* root = root_loc->load();
for (auto* ptr = root; ptr;) {
auto* node = get_node(ptr);
if (key_equal()(const_key_projection()(node->value), key)) {
return iterator(storage, i, node);
}
ptr = node->prev.load();
}
return end();
}
/*
* This operation by itself is always thread-safe. However, any mutating
* operations (concurrent or synchronous) invalidate all iterators.
*/
const_iterator find(const key_type& key) const {
auto hash = hasher()(key);
auto* storage = m_storage.load();
auto* ptrs = storage->ptrs;
size_t i = hash % storage->size;
auto* root_loc = &ptrs[i];
auto* root = root_loc->load();
for (auto* ptr = root; ptr;) {
auto* node = get_node(ptr);
if (key_equal()(const_key_projection()(node->value), key)) {
return const_iterator(storage, i, node);
}
ptr = node->prev.load();
}
return end();
}
/*
* This operation is always thread-safe.
*/
size_t size() const { return m_count.load(); }
/*
* This operation is always thread-safe.
*/
bool empty() const { return size() == 0; }
/*
* This operation is NOT thread-safe.
*/
void clear(size_t size = INITIAL_SIZE) {
if (m_count.load() > 0) {
Storage::destroy(m_storage.exchange(Storage::create(size, nullptr)));
m_count.store(0);
}
compact();
}
ConcurrentHashtable() noexcept
: m_storage(Storage::create()), m_count(0), m_erased(nullptr) {}
/*
* This operation is NOT thread-safe.
*/
ConcurrentHashtable(const ConcurrentHashtable& container) noexcept
: m_storage(Storage::create(container.size() / LOAD_FACTOR + 1, nullptr)),
m_count(0),
m_erased(nullptr) {
for (const auto& p : container) {
try_insert(p);
}
}
/*
* This operation is NOT thread-safe.
*/
ConcurrentHashtable(ConcurrentHashtable&& container) noexcept
: m_storage(container.m_storage.exchange(Storage::create())),
m_count(container.m_count.exchange(0)),
m_erased(container.m_erased.exchange(nullptr)) {
compact();
}
/*
* This operation is NOT thread-safe.
*/
ConcurrentHashtable& operator=(ConcurrentHashtable&& container) noexcept {
clear();
container.compact();
m_storage.store(container.m_storage.exchange(m_storage.load()));
m_count.store(container.m_count.exchange(0));
return *this;
}
/*
* This operation is NOT thread-safe.
*/
ConcurrentHashtable& operator=(
const ConcurrentHashtable& container) noexcept {
if (this != &container) {
clear(container.size() / LOAD_FACTOR + 1);
for (const auto& p : container) {
try_insert(p);
}
}
return *this;
}
/*
* This operation releases all memory and leaves behind the object in an
* uninitialized state.
*/
void destroy() {
Storage::destroy(m_storage.exchange(nullptr));
m_count.store(0);
process_erased();
}
~ConcurrentHashtable() { destroy(); }
/*
* This operation is always thread-safe.
*/
value_type* get(const key_type& key) {
auto hash = hasher()(key);
auto* storage = m_storage.load();
do {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
for (auto* node = get_node(root); node;
node = get_node(node->prev.load())) {
if (key_equal()(const_key_projection()(node->value), key)) {
return &node->value;
}
}
storage = storage->next.load();
} while (storage);
return nullptr;
}
/*
* This operation is always thread-safe.
*/
const value_type* get(const key_type& key) const {
auto hash = hasher()(key);
auto* storage = m_storage.load();
do {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
for (auto* node = get_node(root); node;
node = get_node(node->prev.load())) {
if (key_equal()(const_key_projection()(node->value), key)) {
return &node->value;
}
}
storage = storage->next.load();
} while (storage);
return nullptr;
}
/*
* This operation is always thread-safe.
*/
template <typename... Args>
insertion_result try_emplace(const key_type& key, Args&&... args) {
Node* new_node = nullptr;
auto hash = hasher()(key);
auto* storage = m_storage.load();
while (true) {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
for (auto* node = get_node(root); node;
node = get_node(node->prev.load())) {
if (key_equal()(const_key_projection()(node->value), key)) {
return insertion_result(&node->value, new_node);
}
}
if (is_moved_or_locked(root)) {
if (auto* next_storage = storage->next.load()) {
storage = next_storage;
continue;
}
// We are racing with an erasure; assume it's not affecting us.
root = get_node(root);
}
if (load_factor_exceeded(storage) && reserve(storage->size * 2)) {
storage = m_storage.load();
continue;
}
if (!new_node) {
new_node =
new Node(ConstRefKeyArgsTag(), key, std::forward<Args>(args)...);
}
new_node->prev = root;
if (root_loc->compare_exchange_strong(root, new_node)) {
m_count.fetch_add(1);
return insertion_result(&new_node->value);
}
// We lost a race with another insertion
}
}
/*
* This operation is always thread-safe.
*/
template <typename... Args>
insertion_result try_emplace(key_type&& key, Args&&... args) {
Node* new_node = nullptr;
auto hash = hasher()(key);
auto* storage = m_storage.load();
const key_type* key_ptr = &key;
while (true) {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
for (auto* node = get_node(root); node;
node = get_node(node->prev.load())) {
if (key_equal()(const_key_projection()(node->value), *key_ptr)) {
return insertion_result(&node->value, new_node);
}
}
if (is_moved_or_locked(root)) {
if (auto* next_storage = storage->next.load()) {
storage = next_storage;
continue;
}
// We are racing with an erasure; assume it's not affecting us.
root = get_node(root);
}
if (load_factor_exceeded(storage) && reserve(storage->size * 2)) {
storage = m_storage.load();
continue;
}
if (!new_node) {
new_node = new Node(RvalueRefKeyArgsTag(), std::forward<key_type>(key),
std::forward<Args>(args)...);
key_ptr = &const_key_projection()(new_node->value);
}
new_node->prev = root;
if (root_loc->compare_exchange_strong(root, new_node)) {
m_count.fetch_add(1);
return insertion_result(&new_node->value);
}
// We lost a race with another insertion
}
}
/*
* This operation is always thread-safe.
*/
insertion_result try_insert(const value_type& value) {
Node* new_node = nullptr;
auto hash = hasher()(const_key_projection()(value));
auto* storage = m_storage.load();
while (true) {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
for (auto* node = get_node(root); node;
node = get_node(node->prev.load())) {
if (key_equal()(const_key_projection()(node->value),
const_key_projection()(value))) {
return insertion_result(&node->value, new_node);
}
}
if (is_moved_or_locked(root)) {
if (auto* next_storage = storage->next.load()) {
storage = next_storage;
continue;
}
// We are racing with an erasure; assume it's not affecting us.
root = get_node(root);
}
if (load_factor_exceeded(storage) && reserve(storage->size * 2)) {
storage = m_storage.load();
continue;
}
if (!new_node) {
new_node = new Node(ConstRefValueTag(), value);
}
new_node->prev = root;
if (root_loc->compare_exchange_strong(root, new_node)) {
m_count.fetch_add(1);
return insertion_result(&new_node->value);
}
// We lost a race with another insertion
}
}
/*
* This operation is always thread-safe.
*/
insertion_result try_insert(value_type&& value) {
Node* new_node = nullptr;
auto hash = hasher()(const_key_projection()(value));
auto* storage = m_storage.load();
auto* value_ptr = &value;
while (true) {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
for (auto* node = get_node(root); node;
node = get_node(node->prev.load())) {
if (key_equal()(const_key_projection()(node->value),
const_key_projection()(*value_ptr))) {
// We lost a race with an equivalent insertion
return insertion_result(&node->value, new_node);
}
}
if (is_moved_or_locked(root)) {
if (auto* next_storage = storage->next.load()) {
storage = next_storage;
continue;
}
// We are racing with an erasure; assume it's not affecting us.
root = get_node(root);
}
if (load_factor_exceeded(storage) && reserve(storage->size * 2)) {
storage = m_storage.load();
continue;
}
if (!new_node) {
new_node =
new Node(RvalueRefValueTag(), std::forward<value_type>(value));
value_ptr = &new_node->value;
}
new_node->prev = root;
if (root_loc->compare_exchange_strong(root, new_node)) {
m_count.fetch_add(1);
return insertion_result(&new_node->value);
}
// We lost a race with another insertion
}
}
/*
* This operation is always thread-safe.
*/
bool reserve(size_t capacity) {
bool resizing = false;
if (!m_resizing.compare_exchange_strong(resizing, true)) {
return false;
}
auto* storage = m_storage.load();
if (storage->size >= capacity) {
m_resizing.store(false);
return true;
}
auto timer_scope = s_reserving.scope();
auto new_capacity = get_prime_number_greater_or_equal_to(capacity);
auto* ptrs = storage->ptrs;
auto* new_storage = Storage::create(new_capacity, storage);
storage->next.store(new_storage);
std::stack<std::atomic<Ptr>*> locs;
for (size_t i = 0; i < storage->size; ++i) {
std::atomic<Ptr>* loc = &ptrs[i];
// Lock the bucket (or mark the bucket as moved if its empty). This might
// fail due to a race with an insertion or erasure
Ptr ptr = nullptr;
Node* node = nullptr;
while (!loc->compare_exchange_strong(ptr, moved_or_lock(node))) {
node = get_node(ptr);
ptr = node;
}
if (node == nullptr) {
continue;
}
// Lets rewire the nodes from the back to the new storage version.
locs.push(loc);
auto* prev_loc = &node->prev;
auto* prev_ptr = prev_loc->load();
while (prev_ptr) {
loc = prev_loc;
locs.push(loc);
ptr = prev_ptr;
node = get_node(ptr);
prev_loc = &node->prev;
prev_ptr = prev_loc->load();
}
while (!locs.empty()) {
loc = locs.top();
locs.pop();
ptr = loc->load();
node = get_node(ptr);
prev_loc = &node->prev;
prev_ptr = prev_loc->load();
always_assert(prev_ptr == nullptr || is_moved_or_locked(prev_ptr));
auto new_hash = hasher()(const_key_projection()(node->value));
auto* new_loc = &new_storage->ptrs[new_hash % new_storage->size];
auto* new_ptr = new_loc->load();
// Rewiring the node happens in three steps:
do {
// Assume there is no race with an erasure.
new_ptr = get_node(new_ptr);
// 1. Set the (null) prev node pointer to the first chain element in
// the new storage version. This is ultimately what we want it to be;
// it might allow a racing read operation to scan irrelevant nodes,
// but that is not a problem for correctness.
prev_loc->store(new_ptr);
// 2. Wire up the current node pointer to be the first chain element
// in the new storage version. This may fail due to a race with
// another thread inserting into or erasing from the same chain. But
// then we'll just retry.
} while (!new_loc->compare_exchange_strong(new_ptr, node));
// 3. Detach the current node pointer from the end of the old chain.
loc->store(moved());
}
}
auto* old_storage = m_storage.exchange(new_storage);
always_assert(old_storage == storage);
m_resizing.store(false);
return true;
}
/*
* This operation is always thread-safe.
*/
value_type* erase(const key_type& key) {
auto hash = hasher()(key);
auto* storage = m_storage.load();
while (true) {
auto* ptrs = storage->ptrs;
auto* root_loc = &ptrs[hash % storage->size];
auto* root = root_loc->load();
if (root == nullptr) {
return nullptr;
}
if (root == moved()) {
storage = storage->next.load();
continue;
}
// The chain is not empty. Try to lock the bucket. This might fail due
// to a race with an insertion, erasure, or resizing.
auto* node = get_node(root);
always_assert(node);
root = node;
if (!root_loc->compare_exchange_strong(root, lock(node))) {
continue;
}
auto* loc = root_loc;
for (; node && !key_equal()(const_key_projection()(node->value), key);
loc = &node->prev, node = get_node(loc->load())) {
}
if (node) {
// Erase node.
loc->store(node->prev.load());
m_count.fetch_sub(1);
// Store erased node for later actual deletion.
auto* erased = new Erased{node, nullptr};
while (!m_erased.compare_exchange_strong(erased->prev, erased)) {
}
}
if (loc != root_loc) {
// Unlock root node (as we didn't erase it).
root_loc->store(root);
}
return node ? &node->value : nullptr;
}
}
/*
* This operation is NOT thread-safe.
*/
void compact() {
process_erased();
auto* storage = m_storage.load();
always_assert(storage->next.load() == nullptr);
Storage* prev_storage = nullptr;
std::swap(storage->prev, prev_storage);
Storage::destroy(prev_storage);
}
private:
static constexpr float LOAD_FACTOR = 0.75;
static constexpr size_t INITIAL_SIZE = 5;
// We store Node pointers as tagged values, to indicate, and be able to
// atomically update, whether a location where a node pointer is stored is
// currently involved in an erasure or resizing operation.
using Ptr = void*;
static const size_t MOVED_OR_LOCKED = 1;
using PtrPlusBits = boost::intrusive::pointer_plus_bits<Ptr, 1>;
struct ConstRefValueTag {};
struct RvalueRefValueTag {};
struct ConstRefKeyArgsTag {};
struct RvalueRefKeyArgsTag {};
struct Node {
value_type value;
std::atomic<Ptr> prev{nullptr};
explicit Node(ConstRefValueTag, const value_type& value) : value(value) {}
explicit Node(RvalueRefValueTag, value_type&& value)
: value(std::forward<value_type>(value)) {}
template <typename key_type2 = key_type,
typename = typename std::enable_if_t<
std::is_same_v<key_type2, value_type>>>
explicit Node(ConstRefKeyArgsTag, const key_type2& key) : value(key) {}
template <typename key_type2 = key_type,
typename = typename std::enable_if_t<
std::is_same_v<key_type2, value_type>>>
explicit Node(RvalueRefKeyArgsTag, key_type2&& key)
: value(std::forward<key_type2>(key)) {}
template <typename key_type2 = key_type,
typename = typename std::enable_if_t<
!std::is_same_v<key_type2, value_type>>,
typename... Args>
explicit Node(ConstRefKeyArgsTag, const key_type2& key, Args&&... args)
: value(std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(std::forward<Args>(args)...)) {}
template <typename key_type2 = key_type,
typename = typename std::enable_if_t<
!std::is_same_v<key_type2, value_type>>,
typename... Args>
explicit Node(RvalueRefKeyArgsTag, key_type2&& key, Args&&... args)
: value(std::piecewise_construct,
std::forward_as_tuple(std::forward<key_type2>(key)),
std::forward_as_tuple(std::forward<Args>(args)...)) {}
};
// Initially, and every time we resize, a new Storage version is created.
struct Storage {
size_t size;
Storage* prev;
std::atomic<Storage*> next;
std::atomic<Ptr> ptrs[1];
// Only create instances via `create`.
Storage() = delete;
static Storage* create(size_t size, Storage* prev) {
always_assert(size > 0);
size_t bytes = sizeof(Storage) + sizeof(std::atomic<Ptr>) * (size - 1);
always_assert(bytes % sizeof(size_t) == 0);
auto* storage = (Storage*)calloc(bytes / sizeof(size_t), sizeof(size_t));
always_assert(storage);
always_assert(storage->prev == nullptr);
storage->size = size;
storage->prev = prev;
return storage;
}
static Storage* create() { return create(INITIAL_SIZE, nullptr); }
static void destroy(Storage* t) {
for (auto* s = t; s; s = t) {
if (s->next.load() == nullptr) {
for (size_t i = 0; i < s->size; i++) {
auto* loc = &s->ptrs[i];
auto* ptr = loc->load();
for (auto* node = get_node(ptr); node; node = get_node(ptr)) {
ptr = node->prev.load();
delete node;
}
}
}
t = s->prev;
free(s);
}
}
};
std::atomic<Storage*> m_storage;
std::atomic<size_t> m_count;
std::atomic<bool> m_resizing{false};
struct Erased {
Node* node;
Erased* prev;
};
std::atomic<Erased*> m_erased;
bool load_factor_exceeded(const Storage* storage) const {
return m_count.load() > storage->size * LOAD_FACTOR;
}
// Whether more elements can be found in the next Storage version, or if an
// erasure is ongoing.
static bool is_moved_or_locked(Ptr ptr) {
return PtrPlusBits::get_bits(ptr) != 0;
}
static Node* get_node(Ptr ptr) {
return static_cast<Node*>(PtrPlusBits::get_pointer(ptr));
}
// Creates a tagged `Ptr` indicating that this is a sentinel due to resizing;
// if so, additional nodes may be found in the next Storage version.
static Ptr moved() {
Ptr ptr = nullptr;
PtrPlusBits::set_bits(ptr, MOVED_OR_LOCKED);
return ptr;
}
// Creates a tagged root node indicating that the node chain is in the process
// of being resized or part of it is being erased. If there is a next Storage
// version, any additional nodes must go to it.
static Ptr lock(Node* node) {
always_assert(node);
Ptr ptr = node;
PtrPlusBits::set_bits(ptr, MOVED_OR_LOCKED);
return ptr;
}
// Creates a tagged `Ptr` either indicating that the bucket moved if the node
// is absent, or locking the given node.
static Ptr moved_or_lock(Node* node) {
Ptr ptr = node;
PtrPlusBits::set_bits(ptr, MOVED_OR_LOCKED);
return ptr;
}
void process_erased() {
for (auto* erased = m_erased.load(); erased != nullptr;) {
delete erased->node;
auto* prev = erased->prev;
delete erased;
erased = prev;
}
m_erased.store(nullptr);
}
friend class ConcurrentHashtableIterator<
ConcurrentHashtable<Key, Value, Hash, KeyEqual>>;
friend class ConcurrentHashtableIterator<
const ConcurrentHashtable<Key, Value, Hash, KeyEqual>>;
friend class ConcurrentHashtableInsertionResult<
ConcurrentHashtable<Key, Value, Hash, KeyEqual>>;
};
/*
* Helper class to represent result of an (attmpted) insertion. What's
* interesting is that even when insertion fails, because a value with the same
* key is already present in the hashtable, a new value might have been
* incidentally constructed, possibly moving the supplied arguments in the
* process. This result value captures such an incidentally created value, and
* allows checking for equality with the stored value.
*/
template <typename ConcurrentHashtable>
class ConcurrentHashtableInsertionResult final {
using value_type = typename ConcurrentHashtable::value_type;
using Node = typename ConcurrentHashtable::Node;
std::unique_ptr<Node> m_node;
explicit ConcurrentHashtableInsertionResult(value_type* stored_value_ptr)
: stored_value_ptr(stored_value_ptr), success(true) {}
ConcurrentHashtableInsertionResult(value_type* stored_value_ptr, Node* node)
: m_node(node), stored_value_ptr(stored_value_ptr), success(false) {}
public:
value_type* stored_value_ptr;
bool success;
value_type* incidentally_constructed_value() const {
return m_node ? &m_node->value : nullptr;
}
friend ConcurrentHashtable;
};
template <typename ConcurrentHashtable>
class ConcurrentHashtableIterator final {
public:
using difference_type = std::ptrdiff_t;
using value_type = typename ConcurrentHashtable::value_type;
using pointer =
std::conditional_t<std::is_const<ConcurrentHashtable>::value,
typename ConcurrentHashtable::const_pointer,
typename ConcurrentHashtable::pointer>;
using const_pointer = typename ConcurrentHashtable::const_pointer;
using reference =
std::conditional_t<std::is_const<ConcurrentHashtable>::value,
typename ConcurrentHashtable::const_reference,
typename ConcurrentHashtable::reference>;
using const_reference = typename ConcurrentHashtable::const_reference;
using iterator_category = std::forward_iterator_tag;
private:
using Storage = typename ConcurrentHashtable::Storage;
using Node = typename ConcurrentHashtable::Node;
Storage* m_storage;
size_t m_index;
Node* m_node;
bool is_end() const { return m_index == m_storage->size; }
void advance() {
if (m_node) {
m_node = ConcurrentHashtable::get_node(m_node->prev.load());
if (m_node) {
return;
}
}
do {
if (++m_index == m_storage->size) {
return;
}
m_node = ConcurrentHashtable::get_node(m_storage->ptrs[m_index].load());
} while (!m_node);
}
ConcurrentHashtableIterator(Storage* storage, size_t index, Node* node)
: m_storage(storage), m_index(index), m_node(node) {
if (!node && index < storage->size) {
advance();
}
}
public:
ConcurrentHashtableIterator& operator++() {
always_assert(!is_end());
advance();
return *this;
}
ConcurrentHashtableIterator& operator++(int) {
ConcurrentHashtableIterator retval = *this;
++(*this);
return retval;
}
bool operator==(const ConcurrentHashtableIterator& other) const {
return m_storage == other.m_storage && m_index == other.m_index &&
m_node == other.m_node;
}
bool operator!=(const ConcurrentHashtableIterator& other) const {
return !(*this == other);
}
reference operator*() {
always_assert(!is_end());
return m_node->value;
}
pointer operator->() {
always_assert(!is_end());
return &m_node->value;
}
const_reference operator*() const {
always_assert(!is_end());
return m_node->value;
}
const_pointer operator->() const {
always_assert(!is_end());
return &m_node->value;
}
friend ConcurrentHashtable;
};
} // namespace cc_impl
// Use this scope at the top-level function of your application to allow for
// fast concurrent destruction. Avoid changing the threshold in the global scope
// due to hard to control global destruction order, and our dependency on
// threading / the sparta-workqueue for concurrent destruction.
class ConcurrentContainerConcurrentDestructionScope {
size_t m_last_threshold;
public:
explicit ConcurrentContainerConcurrentDestructionScope(
size_t threshold = 4096)
: m_last_threshold(threshold) {
std::swap(cc_impl::s_concurrent_destruction_threshold, m_last_threshold);
}
~ConcurrentContainerConcurrentDestructionScope() {
std::swap(cc_impl::s_concurrent_destruction_threshold, m_last_threshold);
}
};
/*
* This class implements the common functionalities of concurrent sets and maps.
* A concurrent container is a collection of a ConcurrentHashtable
* (providing functionality similar yo unordered_map/unordered_set) arranged in
* slots. Whenever a thread performs a concurrent operation on an element, the
* slot is uniquely determined by the hash code of the element. A sharded lock
* is obtained if the operation in question cannot be performed lock-free. A
* high number of slots may help reduce thread contention at the expense of a
* larger memory footprint. It is advised to use a prime number for `n_slots`,
* so as to ensure a more even spread of elements across slots.
*
* There are two major modes in which a concurrent container is thread-safe:
* - Read only: multiple threads access the contents of the container but do
* not attempt to modify any element.
* - Write only: multiple threads update the contents of the container but do
* not otherwise attempt to access any element.
* The few operations that are thread-safe regardless of the access mode are
* documented as such.
*/
template <typename Container, size_t n_slots>
class ConcurrentContainer {
public:
static_assert(n_slots > 0, "The concurrent container has no slots");
using Key = typename Container::key_type;
using Hash = typename Container::hasher;
using KeyEqual = typename Container::key_equal;
using Value = typename Container::value_type;
using ConcurrentHashtable =
cc_impl::ConcurrentHashtable<Key, Value, Hash, KeyEqual>;
using iterator =
cc_impl::ConcurrentContainerIterator<ConcurrentHashtable, n_slots>;
using const_iterator =
cc_impl::ConcurrentContainerIterator<const ConcurrentHashtable, n_slots>;
virtual ~ConcurrentContainer() {
auto timer_scope = cc_impl::s_destructor.scope();
if (!cc_impl::is_thread_pool_active() ||
size() <= cc_impl::s_concurrent_destruction_threshold) {
for (size_t slot = 0; slot < n_slots; ++slot) {
m_slots[slot].destroy();
}
return;
}
cc_impl::workqueue_run_for(
0, n_slots, [this](size_t slot) { m_slots[slot].destroy(); });
}