This repository has been archived by the owner on Dec 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcuckoohash_map.hh
2119 lines (1907 loc) · 81.8 KB
/
cuckoohash_map.hh
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
#ifndef _CUCKOOHASH_MAP_HH
#define _CUCKOOHASH_MAP_HH
#include <algorithm>
#include <array>
#include <atomic>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <limits>
#include <list>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "cuckoohash_config.h"
#include "cuckoohash_util.h"
//! cuckoohash_map is the hash table class.
template <class Key, class T, class Hash = std::hash<Key>,
class Pred = std::equal_to<Key> >
class cuckoohash_map {
public:
//! key_type is the type of keys.
typedef Key key_type;
//! value_type is the type of key-value pairs.
typedef std::pair<Key, T> value_type;
//! mapped_type is the type of values.
typedef T mapped_type;
//! hasher is the type of the hash function.
typedef Hash hasher;
//! key_equal is the type of the equality predicate.
typedef Pred key_equal;
//! Class returned by operator[] which wraps an entry in the hash table.
//! Note that this reference type behave somewhat differently from an STL
//! map reference. Most importantly, running this operator will not insert a
//! default key-value pair into the map if the given key is not already in
//! the map.
class reference {
// Note that this implementation here is not exactly STL compliant. To
// maintain performance and avoid hitting the hash table too many times,
// The reference object is *lazy*. In other words,
//
// - operator[] does not actually perform an insert. It returns a
// reference object pointing to the requested key.
// - On table[i] = val // reference::operator=(mapped_type)
// an update / insert is called
// - On table[i] = table[j] // reference::operator=(const reference&)
// an update / insert is called with the value of table[j]
// - On val = table[i] // operator mapped_type()
// a find is called
// - On table[i] (i.e. no operation performed)
// the destructor is called immediately (reference::~reference())
// and nothing happens.
public:
//! Delete the default constructor, which should never be used
reference() = delete;
//! Casting to \p mapped_type runs a find for the stored key. If the
//! find fails, it will thrown an exception.
operator mapped_type() const {
return owner_.find(key_);
}
//! The assignment operator will first try to update the value at the
//! reference's key. If the key isn't in the table, it will insert the
//! key with \p val.
reference& operator=(const mapped_type& val) {
owner_.upsert(
key_, [&val](mapped_type& v) { v = val; }, val);
return *this;
}
//! The copy assignment operator doesn't actually copy the passed-in
//! reference. Instead, it has the same behavior as operator=(const
//! mapped_type& val).
reference& operator=(const reference& ref) {
*this = (mapped_type) ref;
return *this;
}
private:
// private constructor which initializes the owner and key
reference(cuckoohash_map& owner, const key_type& key)
: owner_(owner), key_(key) {}
// reference to the hash map instance
cuckoohash_map& owner_;
// the referenced key
const key_type& key_;
// cuckoohash_map needs to call the private constructor
friend class cuckoohash_map;
};
typedef mapped_type const_reference;
private:
// Constants used internally
// true if the key is small and simple, which means using partial keys would
// probably slow us down
static const bool is_simple =
std::is_pod<key_type>::value && sizeof(key_type) <= 8;
static const bool value_copy_assignable = std::is_copy_assignable<
mapped_type>::value;
// number of locks in the locks_ array
static const size_t kNumLocks = 1 << 13;
// number of cores on the machine
static const size_t kNumCores;
// The maximum number of cuckoo operations per insert. This must be less
// than or equal to SLOT_PER_BUCKET^(MAX_BFS_DEPTH+1)
static const size_t MAX_CUCKOO_COUNT = 500;
// The maximum depth of a BFS path
static const size_t MAX_BFS_DEPTH = 4;
// Structs and functions used internally
__declspec(align(64)) class spinlock {
std::atomic_flag lock_;
public:
spinlock() {
lock_.clear();
}
inline void lock() {
while (lock_.test_and_set(std::memory_order_acquire));
}
inline void unlock() {
lock_.clear(std::memory_order_release);
}
inline bool try_lock() {
return !lock_.test_and_set(std::memory_order_acquire);
}
};
typedef enum {
ok = 0,
failure = 1,
failure_key_not_found = 2,
failure_key_duplicated = 3,
failure_space_not_enough = 4,
failure_function_not_supported = 5,
failure_table_full = 6,
failure_under_expansion = 7,
} cuckoo_status;
typedef char partial_t;
// Two partial key containers. One for when we're actually using partial
// keys and another that mocks partial keys for when the type is simple. The
// bucket will derive the correct class depending on whether the type is
// simple or not.
class RealPartialContainer {
std::array<partial_t, SLOT_PER_BUCKET> partials_;
public:
const partial_t& partial(int ind) const {
return partials_[ind];
}
partial_t& partial(int ind) {
return partials_[ind];
}
};
class FakePartialContainer {
public:
// These methods should never be called, so we raise an exception if
// they are.
const partial_t& partial(int) const {
throw std::logic_error(
"FakePartialContainer::partial should never be called");
}
partial_t& partial(int) {
throw std::logic_error(
"FakePartialContainer::partial should never be called");
}
};
// The Bucket type holds SLOT_PER_BUCKET keys and values, and a occupied
// bitset, which indicates whether the slot at the given bit index is in
// the table or not. It uses aligned_storage arrays to store the keys and
// values to allow constructing and destroying key-value pairs in place.
class Bucket : public std::conditional<is_simple, FakePartialContainer,
RealPartialContainer>::type {
private:
std::array<typename std::aligned_storage<
sizeof(key_type), std::alignment_of<key_type>::value>::type,
SLOT_PER_BUCKET> keys_;
std::array<typename std::aligned_storage<
sizeof(mapped_type), std::alignment_of<mapped_type>::value>::type,
SLOT_PER_BUCKET> vals_;
std::bitset<SLOT_PER_BUCKET> occupied_;
// key_allocator is the allocator used to construct keys
static std::allocator<key_type> key_allocator;
// value_allocator is the allocator to construct values
static std::allocator<mapped_type> value_allocator;
public:
bool occupied(int ind) const {
return occupied_.test(ind);
}
const key_type& key(int ind) const {
return *static_cast<const key_type*>(
static_cast<const void*>(&keys_[ind]));
}
key_type& key(int ind) {
return *static_cast<key_type*>(static_cast<void*>(&keys_[ind]));
}
const mapped_type& val(int ind) const {
return *static_cast<const mapped_type*>(
static_cast<const void*>(&vals_[ind]));
}
mapped_type& val(int ind) {
return *static_cast<mapped_type*>(static_cast<void*>(&vals_[ind]));
}
template <class V>
void setKV(size_t ind, const key_type& k, V v) {
occupied_.set(ind);
key_allocator.construct(&key(ind), k);
value_allocator.construct(&val(ind), std::forward<V>(v));
}
void eraseKV(size_t ind) {
occupied_.reset(ind);
key_allocator.destroy(&key(ind));
value_allocator.destroy(&val(ind));
}
Bucket() {
occupied_.reset();
}
~Bucket() {
for (size_t i = 0; i < SLOT_PER_BUCKET; ++i) {
if (occupied(i)) {
eraseKV(i);
}
}
}
};
// cacheint is a cache-aligned atomic integer type.
__declspec(align(64)) struct cacheint {
std::atomic<size_t> num;
cacheint(): num(0) {}
cacheint(size_t x): num(x) {}
cacheint(cacheint&& x): num(x.num.load()) {}
};
// An alias for the type of lock we are using
typedef spinlock locktype;
// TableInfo contains the entire state of the hashtable. We allocate one
// TableInfo pointer per hash table and store all of the table memory in it,
// so that all the data can be atomically swapped during expansion.
struct TableInfo {
// 2**hashpower is the number of buckets
size_t hashpower_;
// vector of buckets
std::vector<Bucket> buckets_;
// array of locks
std::array<locktype, kNumLocks> locks_;
// per-core counters for the number of inserts and deletes
std::vector<cacheint> num_inserts, num_deletes;
// The constructor allocates the memory for the table. It allocates one
// cacheint for each core in num_inserts and num_deletes.
TableInfo(const size_t hashpower)
: hashpower_(hashpower), buckets_(hashsize(hashpower_)),
num_inserts(kNumCores), num_deletes(kNumCores) {}
~TableInfo() {}
};
// This is a hazard pointer, used to indicate which version of the TableInfo
// is currently being used in the thread. Since cuckoohash_map operations
// can run simultaneously in different threads, this variable is thread
// local. Note that this variable can be safely shared between different
// cuckoohash_map instances, since multiple operations cannot occur
// simultaneously in one thread. The hazard pointer variable points to a
// pointer inside a global list of pointers, that each map checks before
// deleting any old TableInfo pointers.
static __declspec(thread) TableInfo** hazard_pointer;
// A GlobalHazardPointerList stores a list of pointers that cannot be
// deleted by an expansion thread. Each thread gets its own node in the
// list, whose data pointer it can modify without contention.
class GlobalHazardPointerList {
std::list<TableInfo*> hp_;
std::mutex lock_;
public:
// new_hazard_pointer creates and returns a new hazard pointer for a
// thread.
TableInfo** new_hazard_pointer() {
std::unique_lock<std::mutex> ul(lock_);
hp_.emplace_back(nullptr);
return &hp_.back();
}
// delete_unused scans the list of hazard pointers, deleting any
// pointers in old_pointers that aren't in this list. If it does delete
// a pointer in old_pointers, it deletes that node from the list.
void delete_unused(std::list<std::unique_ptr<TableInfo>>&
old_pointers) {
std::unique_lock<std::mutex> ul(lock_);
old_pointers.remove_if(
[this](const std::unique_ptr<TableInfo>& ptr) {
return std::find(hp_.begin(), hp_.end(), ptr.get()) ==
hp_.end();
});
}
};
// As long as the thread_local hazard_pointer is static, which means each
// template instantiation of a cuckoohash_map class gets its own per-thread
// hazard pointer, then each template instantiation of a cuckoohash_map
// class can get its own global_hazard_pointers list, since different
// template instantiations won't interfere with each other.
static GlobalHazardPointerList global_hazard_pointers;
// check_hazard_pointer should be called before any public method that loads
// a table snapshot. It checks that the thread local hazard pointer pointer
// is not null, and gets a new pointer if it is null.
static inline void check_hazard_pointer() {
if (hazard_pointer == nullptr) {
hazard_pointer = global_hazard_pointers.new_hazard_pointer();
}
}
// Once a function is finished with a version of the table, it will want to
// unset the hazard pointer it set so that it can be freed if it needs to.
// This is an object which, upon destruction, will unset the hazard pointer.
class HazardPointerUnsetter {
public:
~HazardPointerUnsetter() {
*hazard_pointer = nullptr;
}
};
// counterid stores the per-thread counter index of each thread.
static __declspec(thread) int counterid;
// check_counterid checks if the counterid has already been determined. If
// not, it assigns a counterid to the current thread by picking a random
// core. This should be called at the beginning of any function that changes
// the number of elements in the table.
static inline void check_counterid() {
if (counterid < 0) {
counterid = rand() % kNumCores;
}
}
// reserve_calc takes in a parameter specifying a certain number of slots
// for a table and returns the smallest hashpower that will hold n elements.
static size_t reserve_calc(size_t n) {
double nhd = ceil(log2((double)n / (double)SLOT_PER_BUCKET));
size_t new_hashpower = (size_t) (nhd <= 0 ? 1.0 : nhd);
assert(n <= hashsize(new_hashpower) * SLOT_PER_BUCKET);
return new_hashpower;
}
public:
//! The constructor creates a new hash table with enough space for \p n
//! elements. If the constructor fails, it will throw an exception.
explicit cuckoohash_map(size_t n = DEFAULT_SIZE) {
cuckoo_init(reserve_calc(n));
}
//! The destructor explicitly deletes the current table info.
~cuckoohash_map() {
TableInfo* ti = table_info.load();
if (ti != nullptr) {
delete ti;
}
}
//! clear removes all the elements in the hash table, calling their
//! destructors.
void clear() {
check_hazard_pointer();
TableInfo* ti = snapshot_and_lock_all();
assert(ti == table_info.load());
AllUnlocker au(ti);
HazardPointerUnsetter hpu;
cuckoo_clear(ti);
}
//! size returns the number of items currently in the hash table. Since it
//! doesn't lock the table, elements can be inserted during the computation,
//! so the result may not necessarily be exact.
size_t size() const {
check_hazard_pointer();
const TableInfo* ti = snapshot_table_nolock();
HazardPointerUnsetter hpu;
const size_t s = cuckoo_size(ti);
return s;
}
//! empty returns true if the table is empty.
bool empty() const {
return size() == 0;
}
//! hashpower returns the hashpower of the table, which is
//! log<SUB>2</SUB>(the number of buckets).
size_t hashpower() const {
check_hazard_pointer();
TableInfo* ti = snapshot_table_nolock();
HazardPointerUnsetter hpu;
const size_t hashpower = ti->hashpower_;
return hashpower;
}
//! bucket_count returns the number of buckets in the table.
size_t bucket_count() const {
check_hazard_pointer();
TableInfo* ti = snapshot_table_nolock();
HazardPointerUnsetter hpu;
size_t buckets = hashsize(ti->hashpower_);
return buckets;
}
//! load_factor returns the ratio of the number of items in the table to the
//! total number of available slots in the table.
double load_factor() const {
check_hazard_pointer();
const TableInfo* ti = snapshot_table_nolock();
HazardPointerUnsetter hpu;
return cuckoo_loadfactor(ti);
}
//! find searches through the table for \p key, and stores the associated
//! value it finds in \p val.
ENABLE_IF(, value_copy_assignable, bool)
find(const key_type& key, mapped_type& val) const {
check_hazard_pointer();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
const cuckoo_status st = cuckoo_find(key, val, hv, ti, i1, i2);
unlock_two(ti, i1, i2);
return (st == ok);
}
//! This version of find does the same thing as the two-argument version,
//! except it returns the value it finds, throwing an \p std::out_of_range
//! exception if the key isn't in the table.
ENABLE_IF(, value_copy_assignable, mapped_type)
find(const key_type& key) const {
mapped_type val;
bool done = find(key, val);
if (done) {
return val;
} else {
throw std::out_of_range("key not found in table");
}
}
//! contains searches through the table for \p key, and returns true if it
//! finds it in the table, and false otherwise.
bool contains(const key_type& key) const {
check_hazard_pointer();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
const bool result = cuckoo_contains(key, hv, ti, i1, i2);
unlock_two(ti, i1, i2);
return result;
}
//! insert puts the given key-value pair into the table. It first checks
//! that \p key isn't already in the table, since the table doesn't support
//! duplicate keys. If the table is out of space, insert will automatically
//! expand until it can succeed. Note that expansion can throw an exception,
//! which insert will propagate. If \p key is already in the table, it
//! returns false, otherwise it returns true.
template <class V>
typename std::enable_if<std::is_convertible<V, const mapped_type&>::value,
bool>::type
insert(const key_type& key, V val) {
check_hazard_pointer();
check_counterid();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
return cuckoo_insert_loop(key, std::forward<V>(val),
hv, ti, i1, i2);
}
//! erase removes \p key and it's associated value from the table, calling
//! their destructors. If \p key is not there, it returns false, otherwise
//! it returns true.
bool erase(const key_type& key) {
check_hazard_pointer();
check_counterid();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
const cuckoo_status st = cuckoo_delete(key, hv, ti, i1, i2);
unlock_two(ti, i1, i2);
return (st == ok);
}
//! update changes the value associated with \p key to \p val. If \p key is
//! not there, it returns false, otherwise it returns true.
ENABLE_IF(, value_copy_assignable, bool)
update(const key_type& key, const mapped_type& val) {
check_hazard_pointer();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
const cuckoo_status st = cuckoo_update(key, val, hv, ti, i1, i2);
unlock_two(ti, i1, i2);
return (st == ok);
}
//! update_fn changes the value associated with \p key with the function \p
//! fn. \p fn will be passed one argument of type \p mapped_type& and can
//! modify the argument as desired, returning nothing. If \p key is not
//! there, it returns false, otherwise it returns true.
template <typename Updater>
bool update_fn(const key_type& key, Updater fn) {
check_hazard_pointer();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
const cuckoo_status st = cuckoo_update_fn(key, fn, hv, ti, i1, i2);
unlock_two(ti, i1, i2);
return (st == ok);
}
//! upsert is a combination of update_fn and insert. It first tries updating
//! the value associated with \p key using \p fn. If \p key is not in the
//! table, then it runs an insert with \p key and \p val. It will always
//! succeed, since if the update fails and the insert finds the key already
//! inserted, it can retry the update.
template <typename Updater>
void upsert(const key_type& key, Updater fn, const mapped_type& val) {
check_hazard_pointer();
check_counterid();
size_t hv = hashed_key(key);
TableInfo* ti;
size_t i1, i2;
bool res;
do {
std::tie(ti, i1, i2) = snapshot_and_lock_two(hv);
HazardPointerUnsetter hpu;
const cuckoo_status st = cuckoo_update_fn(key, fn, hv, ti, i1, i2);
if (st == ok) {
unlock_two(ti, i1, i2);
return;
}
// We run an insert, since the update failed
res = cuckoo_insert_loop(key, val, hv, ti, i1, i2);
// The only valid reason for res being false is if insert
// encountered a duplicate key after releasing the locks and
// performing cuckoo hashing. In this case, we retry the entire
// upsert operation.
} while (!res);
return;
}
//! rehash will size the table using a hashpower of \p n. Note that the
//! number of buckets in the table will be 2<SUP>\p n</SUP> after expansion,
//! so the table will have 2<SUP>\p n</SUP> × \ref SLOT_PER_BUCKET
//! slots to store items in. If \p n is not larger than the current
//! hashpower, then the function does nothing. It returns true if the table
//! expansion succeeded, and false otherwise. rehash can throw an exception
//! if the expansion fails to allocate enough memory for the larger table.
bool rehash(size_t n) {
check_hazard_pointer();
TableInfo* ti = snapshot_table_nolock();
HazardPointerUnsetter hpu;
if (n <= ti->hashpower_) {
return false;
}
const cuckoo_status st = cuckoo_expand_simple(n);
return (st == ok);
}
//! reserve will size the table to have enough slots for at least \p n
//! elements. If the table can already hold that many elements, the function
//! has no effect. Otherwise, the function will expand the table to a
//! hashpower sufficient to hold \p n elements. It will return true if there
//! was an expansion, and false otherwise. reserve can throw an exception if
//! the expansion fails to allocate enough memory for the larger table.
bool reserve(size_t n) {
check_hazard_pointer();
TableInfo* ti = snapshot_table_nolock();
HazardPointerUnsetter hpu;
if (n <= hashsize(ti->hashpower_) * SLOT_PER_BUCKET) {
return false;
}
const cuckoo_status st = cuckoo_expand_simple(reserve_calc(n));
return (st == ok);
}
//! hash_function returns the hash function object used by the table.
hasher hash_function() const {
return hashfn;
}
//! key_eq returns the equality predicate object used by the table.
key_equal key_eq() const {
return eqfn;
}
//! Returns a \ref reference to the mapped value stored at the given key.
//! Note that the reference behaves somewhat differently from an STL map
//! reference (see the \ref reference documentation for details).
reference operator[](const key_type& key) {
return (reference(*this, key));
}
//! Returns a \ref const_reference to the mapped value stored at the given
//! key. This is equivalent to running the overloaded \ref find function
//! with no value parameter.
const_reference operator[](const key_type& key) const {
return find(key);
}
private:
std::atomic<TableInfo*> table_info;
// old_table_infos holds pointers to old TableInfos that were replaced
// during expansion. This keeps the memory alive for any leftover
// operations, until they are deleted by the global hazard pointer manager.
std::list<std::unique_ptr<TableInfo>> old_table_infos;
static hasher hashfn;
static key_equal eqfn;
// lock locks the given bucket index.
static inline void lock(TableInfo* ti, const size_t i) {
ti->locks_[lock_ind(i)].lock();
}
// unlock unlocks the given bucket index.
static inline void unlock(TableInfo* ti, const size_t i) {
ti->locks_[lock_ind(i)].unlock();
}
// lock_two locks the two bucket indexes, always locking the earlier index
// first to avoid deadlock. If the two indexes are the same, it just locks
// one.
static void lock_two(TableInfo* ti, size_t i1, size_t i2) {
i1 = lock_ind(i1);
i2 = lock_ind(i2);
if (i1 < i2) {
ti->locks_[i1].lock();
ti->locks_[i2].lock();
} else if (i2 < i1) {
ti->locks_[i2].lock();
ti->locks_[i1].lock();
} else {
ti->locks_[i1].lock();
}
}
// unlock_two unlocks both of the given bucket indexes, or only one if they
// are equal. Order doesn't matter here.
static void unlock_two(TableInfo* ti, size_t i1, size_t i2) {
i1 = lock_ind(i1);
i2 = lock_ind(i2);
ti->locks_[i1].unlock();
if (i1 != i2) {
ti->locks_[i2].unlock();
}
}
// lock_three locks the three bucket indexes in numerical order.
static void lock_three(TableInfo* ti, size_t i1,
size_t i2, size_t i3) {
i1 = lock_ind(i1);
i2 = lock_ind(i2);
i3 = lock_ind(i3);
// If any are the same, we just run lock_two
if (i1 == i2) {
lock_two(ti, i1, i3);
} else if (i2 == i3) {
lock_two(ti, i1, i3);
} else if (i1 == i3) {
lock_two(ti, i1, i2);
} else {
if (i1 < i2) {
if (i2 < i3) {
ti->locks_[i1].lock();
ti->locks_[i2].lock();
ti->locks_[i3].lock();
} else if (i1 < i3) {
ti->locks_[i1].lock();
ti->locks_[i3].lock();
ti->locks_[i2].lock();
} else {
ti->locks_[i3].lock();
ti->locks_[i1].lock();
ti->locks_[i2].lock();
}
} else if (i2 < i3) {
if (i1 < i3) {
ti->locks_[i2].lock();
ti->locks_[i1].lock();
ti->locks_[i3].lock();
} else {
ti->locks_[i2].lock();
ti->locks_[i3].lock();
ti->locks_[i1].lock();
}
} else {
ti->locks_[i3].lock();
ti->locks_[i2].lock();
ti->locks_[i1].lock();
}
}
}
// unlock_three unlocks the three given buckets
static void unlock_three(TableInfo* ti, size_t i1,
size_t i2, size_t i3) {
i1 = lock_ind(i1);
i2 = lock_ind(i2);
i3 = lock_ind(i3);
ti->locks_[i1].unlock();
if (i2 != i1) {
ti->locks_[i2].unlock();
}
if (i3 != i1 && i3 != i2) {
ti->locks_[i3].unlock();
}
}
// snapshot_table_nolock loads the table info pointer and sets the hazard
// pointer, whithout locking anything. There is a possibility that after
// loading a snapshot and setting the hazard pointer, an expansion runs and
// create a new version of the table, leaving the old one for deletion. To
// deal with that, we check that the table_info we loaded is the same as the
// current one, and if it isn't, we try again. Whenever we check if (ti !=
// table_info.load()) after setting the hazard pointer, there is an ABA
// issue, where the address of the new table_info equals the address of a
// previously deleted one, however it doesn't matter, since we would still
// be looking at the most recent table_info in that case.
TableInfo* snapshot_table_nolock() const {
while (true) {
TableInfo* ti = table_info.load();
*hazard_pointer = ti;
// If the table info has changed in the time we set the hazard
// pointer, ti could have been deleted, so try again.
if (ti != table_info.load()) {
continue;
}
return ti;
}
}
// snapshot_and_lock_two loads the table_info pointer and locks the buckets
// associated with the given hash value. It returns the table_info and the
// two locked buckets as a tuple. Since the positions of the bucket locks
// depends on the number of buckets in the table, the table_info pointer
// needs to be grabbed first.
std::tuple<TableInfo*, size_t, size_t>
snapshot_and_lock_two(const size_t hv) const {
TableInfo* ti;
size_t i1, i2;
while (true) {
ti = table_info.load();
*hazard_pointer = ti;
// If the table info has changed in the time we set the hazard
// pointer, ti could have been deleted, so try again.
if (ti != table_info.load()) {
continue;
}
i1 = index_hash(ti, hv);
i2 = alt_index(ti, hv, i1);
lock_two(ti, i1, i2);
// Check the table info again
if (ti != table_info.load()) {
unlock_two(ti, i1, i2);
continue;
}
return std::make_tuple(ti, i1, i2);
}
}
// AllUnlocker is an object which releases all the locks on the given table
// info when it's destructor is called.
class AllUnlocker {
TableInfo* ti_;
public:
AllUnlocker(TableInfo* ti): ti_(ti) {}
~AllUnlocker() {
if (ti_ != nullptr) {
for (size_t i = 0; i < kNumLocks; ++i) {
ti_->locks_[i].unlock();
}
}
}
};
// snapshot_and_lock_all is similar to snapshot_and_lock_two, except that it
// takes all the locks in the table.
TableInfo* snapshot_and_lock_all() const {
while (true) {
TableInfo* ti = table_info.load();
*hazard_pointer = ti;
// If the table info has changed, ti could have been deleted, so try
// again
if (ti != table_info.load()) {
continue;
}
for (size_t i = 0; i < kNumLocks; ++i) {
ti->locks_[i].lock();
}
// If the table info has changed, unlock the locks and try again.
if (ti != table_info.load()) {
AllUnlocker au(ti);
continue;
}
return ti;
}
}
// lock_ind converts an index into buckets_ to an index into locks_.
static inline size_t lock_ind(const size_t bucket_ind) {
return bucket_ind & (kNumLocks - 1);
}
// hashsize returns the number of buckets corresponding to a given
// hashpower.
static inline size_t hashsize(const size_t hashpower) {
return 1U << hashpower;
}
// hashmask returns the bitmask for the buckets array corresponding to a
// given hashpower.
static inline size_t hashmask(const size_t hashpower) {
return hashsize(hashpower) - 1;
}
// hashed_key hashes the given key.
static inline size_t hashed_key(const key_type &key) {
return hashfn(key);
}
// index_hash returns the first possible bucket that the given hashed key
// could be.
static inline size_t index_hash(const TableInfo* ti, const size_t hv) {
return hv & hashmask(ti->hashpower_);
}
// alt_index returns the other possible bucket that the given hashed key
// could be. It takes the first possible bucket as a parameter. Note that
// this function will return the first possible bucket if index is the
// second possible bucket, so alt_index(ti, hv, alt_index(ti, hv,
// index_hash(ti, hv))) == index_hash(ti, hv).
static inline size_t alt_index(
const TableInfo* ti, const size_t hv, const size_t index) {
// ensure tag is nonzero for the multiply
const size_t tag = (hv >> ti->hashpower_) + 1;
// 0x5bd1e995 is the hash constant from MurmurHash2
return (index ^ (tag * 0x5bd1e995)) & hashmask(ti->hashpower_);
}
// partial_key returns a partial_t representing the upper sizeof(partial_t)
// bytes of the hashed key. This is used for partial-key cuckoohashing. If
// the key type is POD and small, we don't use partial keys, so we just
// return 0.
ENABLE_IF(static inline, is_simple, partial_t)
partial_key(const size_t hv) {
return (partial_t)(hv >> ((sizeof(size_t)-sizeof(partial_t)) * 8));
}
ENABLE_IF(static inline, !is_simple, partial_t) partial_key(const size_t&) {
return 0;
}
// CuckooRecord holds one position in a cuckoo path.
typedef struct {
size_t bucket;
size_t slot;
key_type key;
} CuckooRecord;
// b_slot holds the information for a BFS path through the table
__declspec(align(1)) struct b_slot {
// The bucket of the last item in the path
size_t bucket;
// a compressed representation of the slots for each of the buckets in
// the path.
size_t pathcode;
// static_assert(pow(SLOT_PER_BUCKET, MAX_BFS_DEPTH+1) <
// std::numeric_limits<decltype(pathcode)>::max(),
// "pathcode may not be large enough to encode a cuckoo
// path"); The 0-indexed position in the cuckoo path this
// slot occupies
int depth;
b_slot() {}
b_slot(const size_t b, const size_t p, const int d)
: bucket(b), pathcode(p), depth(d) {}
};
// b_queue is the queue used to store b_slots for BFS cuckoo hashing.
__declspec(align(1)) class b_queue {
b_slot slots[MAX_CUCKOO_COUNT+1];
size_t first;
size_t last;
public:
b_queue() : first(0), last(0) {}
void enqueue(b_slot x) {
slots[last] = x;
last = (last == MAX_CUCKOO_COUNT) ? 0 : last+1;
assert(last != first);
}
b_slot dequeue() {
assert(first != last);
b_slot& x = slots[first];
first = (first == MAX_CUCKOO_COUNT) ? 0 : first+1;
return x;
}
bool not_full() {
const size_t next = (last == MAX_CUCKOO_COUNT) ? 0 : last+1;
return next != first;
}
};
// slot_search searches for a cuckoo path using breadth-first search. It
// starts with the i1 and i2 buckets, and, until it finds a bucket with an
// empty slot, adds each slot of the bucket in the b_slot. If the queue runs
// out of space, it fails.
static b_slot slot_search(TableInfo* ti, const size_t i1, const size_t i2) {
b_queue q;
// The initial pathcode informs cuckoopath_search which bucket the path
// starts on
q.enqueue(b_slot(i1, 0, 0));
q.enqueue(b_slot(i2, 1, 0));
while (q.not_full()) {
b_slot x = q.dequeue();
// Picks a random slot to start from
for (size_t slot = 0; slot < SLOT_PER_BUCKET && q.not_full();
++slot) {
lock(ti, x.bucket);
if (!ti->buckets_[x.bucket].occupied(slot)) {
// We can terminate the search here
x.pathcode = x.pathcode * SLOT_PER_BUCKET + slot;
unlock(ti, x.bucket);
return x;
}
// Create a new b_slot item, that represents the bucket we would
// look at after searching x.bucket for empty slots.
const size_t hv = hashed_key(ti->buckets_[x.bucket].key(slot));