-
Notifications
You must be signed in to change notification settings - Fork 4
/
ConcurrentSortedDictionary.cs
2232 lines (2000 loc) · 96.6 KB
/
ConcurrentSortedDictionary.cs
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
/*
MIT License
Copyright (c) 2023 Matthew Krebser (https://github.com/mkrebser)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Used for more nuanced lock testing and sanity test
#define ConcurrentSortedDictionary_DEBUG
// Put this in the concurrent namespace but with 'Extended'
namespace System.Collections.Concurrent.Extended;
public enum InsertResult {
/// <summary>
/// Operation completed successfully.
/// </summary>
success = 0,
/// <summary>
/// Value was not inserted because it already exists.
/// </summary>
alreadyExists = 1,
/// <summary>
/// Value ws not inserted due to timeout.
/// </summary>
timedOut = 2
}
public enum RemoveResult {
/// <summary>
/// Successfully deleted.
/// </summary>
success = 0,
/// <summary>
/// key was not found. No deletion occured.
/// </summary>
notFound = 1,
/// <summary>
/// Value ws not deleted due to timeout.
/// </summary>
timedOut = 2,
}
public enum SearchResult {
/// <summary>
/// Successfully found key.
/// </summary>
success = 0,
/// <summary>
/// key was not found.
/// </summary>
notFound = 1,
/// <summary>
/// Couldn't complete search due to timeout.
/// </summary>
timedOut = 2,
}
// not using the Nullable<T> notation (eg myType? ) because it adds a small overhead to everything
// eg, Nullable<int>[] vs int[] -> Nullable<int> will take up double the memory on many x64 systems due to extra boolean flag
#nullable disable
// Locking Scheme: Multiple Readers & Single Writer
// However, locks are at a granularity of each node- so multiple parts of the tree can be written concurrently
//
// Read Access Scheme: While traversing down the tree hierarchy, reads will aquire the lock of the next
// node they move to before releasing the lock of their current node. This guarentees
// that no writers will skip ahead of any readers. It also guarentees readers will not
// skip ahead of any writers traversing down.
//
// Write Access Scheme: Writers use 'latching'. While traversing downwards.. They will only release a parent node
// if an insert/delete will not cause a spit or merge. (This means that the insert/delete won't
// need to traverse up the B+Tree)
//
// Locks: All locks used are ReaderWriterSlim locks which will prioritize writers
// https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=net-7.0
// An excellent lecture on B+Trees:
// https://courses.cs.washington.edu/courses/cse332/20au/lectures/cse332-20au-lec09-BTrees.pdf
// slides that go over latching (latch-crabbing) https://15721.courses.cs.cmu.edu/spring2017/slides/06-latching.pdf
/// <summary>
/// Implementation of a concurrent B+Tree. https://en.wikipedia.org/wiki/B+tree#
/// </summary>
public partial class ConcurrentSortedDictionary<Key, Value> : IEnumerable<KeyValuePair<Key, Value>> where Key: IComparable<Key> {
private volatile ConcurrentKTreeNode<Key, Value> _root;
public void setRoot(object o) {
this._root = (ConcurrentKTreeNode<Key, Value>)o;
}
private readonly ReaderWriterLockSlim _rootLock;
private long _count;
/// <summary>
/// Number of key-value pairs in the collection. Value may be stale in concurrent access.
/// </summary>
public long Count { get { return _count; } }
/// <summary>
/// Is collection empty? Value may be stale in concurrent access.
/// </summary>
public bool IsEmpty { get { return this.Count <= 0; }}
private volatile int _depth;
/// <summary>
/// Approximate depth of the search tree. Value may be stale in concurrent access.
/// </summary>
public int Depth { get { return _depth + 1; } } // A tree with only root node has _depth = 0
/// <summary>
/// Width of each node in the tree.
/// </summary>
public readonly int k;
/// <summary>
/// Create a new instance of ConcurrentSortedDictionary
/// </summary>
/// <param name="k"> Number of children per node. </param>
public ConcurrentSortedDictionary(int k = 32) {
if (k < 3) // Don't allow '2', it creates potentially many leafs with only 1 item due to b+ tree requirements
throw new ArgumentException("Invalid k specified");
_rootLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
_root = new ConcurrentKTreeNode<Key, Value>(k, isLeaf: true);
_count = 0;
_depth = 0;
this.k = k;
}
public ConcurrentSortedDictionary(ICollection<KeyValuePair<Key, Value>> collection, int k = 32): this(k) {
if (ReferenceEquals(null, collection))
throw new ArgumentException("Cannot input null collection");
foreach (var pair in collection)
AddOrUpdate(pair.Key, pair.Value);
}
public ConcurrentSortedDictionary(ICollection<ValueTuple<Key, Value>> collection, int k = 32): this(k) {
if (ReferenceEquals(null, collection))
throw new ArgumentException("Cannot input null collection");
foreach (var pair in collection)
AddOrUpdate(pair.Item1, pair.Item2);
}
public ConcurrentSortedDictionary(ICollection<Tuple<Key, Value>> collection, int k = 32): this(k) {
if (ReferenceEquals(null, collection))
throw new ArgumentException("Cannot input null collection");
foreach (var pair in collection)
AddOrUpdate(pair.Item1, pair.Item2);
}
public ConcurrentSortedDictionary(ICollection<Key> keys, ICollection<Value> values, int k = 32): this(k) {
if (ReferenceEquals(null, keys) || ReferenceEquals(null, values))
throw new ArgumentException("Cannot input null collection");
foreach (var pair in keys.Zip(values))
AddOrUpdate(pair.Item1, pair.Item2);
}
void assertTimeoutArg(in int timeoutMs) {
if (timeoutMs < 0)
throw new ArgumentException("Timeout cannot be negative!");
}
InsertResult ToInsertResult(in ConcurrentTreeResult_Extended result) {
if (result == ConcurrentTreeResult_Extended.success) {
return InsertResult.success;
} else if (result == ConcurrentTreeResult_Extended.alreadyExists) {
return InsertResult.alreadyExists;
} else {
return InsertResult.timedOut;
}
}
RemoveResult ToRemoveResult(in ConcurrentTreeResult_Extended result) {
if (result == ConcurrentTreeResult_Extended.success) {
return RemoveResult.success;
} else if (result == ConcurrentTreeResult_Extended.notFound) {
return RemoveResult.notFound;
} else {
return RemoveResult.timedOut;
}
}
/// <summary>
/// Insert a Key-Value pair and overwrite if it already exists.
/// </summary>
public InsertResult AddOrUpdate(
in Key key,
in Value value,
in int timeoutMs
) {
assertTimeoutArg(timeoutMs);
Value retrievedValue;
return ToInsertResult(writeToTree(in key, in value, in timeoutMs, LatchAccessType.insert, out retrievedValue, true));
}
/// <summary>
/// Insert a Key-Value pair and overwrite if it already exists. Waits forever for mutex.
/// </summary>
public void AddOrUpdate(
in Key key,
in Value value
) {
Value retrievedValue;
writeToTree(in key, in value, -1, LatchAccessType.insert, out retrievedValue, true);
}
/// <summary>
/// Insert a Key-Value pair or return the existing pair if key already exists.
/// </summary>
public InsertResult TryAdd(
in Key key,
in Value value,
in int timeoutMs
) {
assertTimeoutArg(timeoutMs);
Value retrievedValue;
return ToInsertResult(writeToTree(in key, in value, in timeoutMs, LatchAccessType.insertTest, out retrievedValue, false));
}
/// <summary>
/// Insert a Key-Value pair. Return false if not inserted due to existing value.
/// </summary>
public bool TryAdd(
in Key key,
in Value value
) {
Value retrievedValue;
return ToInsertResult(writeToTree(in key, in value, -1, LatchAccessType.insertTest, out retrievedValue, false)) == InsertResult.success;
}
/// <summary>
/// Insert a Key-Value pair or output the existing pair if key already exists.
/// </summary>
public InsertResult GetOrAdd(
in Key key,
in Value value,
in int timeoutMs,
out Value retrievedValue
) {
assertTimeoutArg(timeoutMs);
return ToInsertResult(writeToTree(in key, in value, in timeoutMs, LatchAccessType.insertTest, out retrievedValue, false));
}
/// <summary>
/// Insert a Key-Value pair if it doesn't exist and return the value. If it does exist, the existing value is returned.
/// </summary>
public Value GetOrAdd(
in Key key,
in Value value
) {
Value retrievedValue;
writeToTree(in key, in value, -1, LatchAccessType.insertTest, out retrievedValue, false);
return retrievedValue;
}
void tryUpdateDepth<LockBuffer>(
int newSearchDepth,
ref Latch<Key, Value> latch,
ref LockBuffer lockBuffer
) where LockBuffer: ILockBuffer<Key, Value> {
if (newSearchDepth >= 30) {
latch.ExitLatchChain(ref lockBuffer);
throw new ArgumentException("Reached 31 tree limit depth. Only a max of "
+ (int)Math.Pow(this.k, 31) + " items is supported. Increasing 'k' will increase limit.");
}
this._depth = newSearchDepth;
}
/// <summary>
/// Perform a insert or delete on the tree depending on the LatchAccessType.
/// </summary>
private ConcurrentTreeResult_Extended writeToTree(
in Key key,
in Value value,
in int timeoutMs,
in LatchAccessType accessType,
out Value retrievedValue,
in bool overwrite = false
) {
if (!typeof(Key).IsValueType && ReferenceEquals(null, key)) {
throw new ArgumentException("Cannot have null key");
}
SearchResultInfo<Key, Value> info = default(SearchResultInfo<Key, Value>);
Value currentValue;
// Optmistic latching
var rwLatch = new Latch<Key, Value>(accessType, this._rootLock, assumeLeafIsSafe: true);
var rwLockBuffer = new LockBuffer2<Key, Value>();
long startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
int remainingMs = getRemainingMs(in startTime, in timeoutMs);
var searchOptions = new SearchOptions(remainingMs, startTime: startTime);
// Perform a query to recurse to the deepest node, latching downwards optimistically
var getResult = ConcurrentKTreeNode<Key, Value>.TryGetValue(in key, out currentValue,
ref info, ref rwLatch, ref rwLockBuffer, this, searchOptions);
// Timeout!
if (getResult == ConcurrentTreeResult_Extended.timedOut) {
retrievedValue = default(Value);
return ConcurrentTreeResult_Extended.timedOut;
}
// If this is a test-before-write- then determine if the test failed
bool exitOnTest = false;
if (accessType == LatchAccessType.insertTest) {
exitOnTest = info.index > -1; // if it is found.. it must have a positive index
} else if (accessType == LatchAccessType.deleteTest) {
exitOnTest = info.index < 0; // if it is not found, it will have a negative index
}
try {
// If we were able to optimistally acquire latch... (or test op was successful)
// The write to tree
if (getResult != ConcurrentTreeResult_Extended.notSafeToUpdateLeaf || exitOnTest) {
#if ConcurrentSortedDictionary_DEBUG
info.node.assertWriterLockHeld();
#endif
if (rwLatch.isInsertAccess) {
tryUpdateDepth(info.depth, ref rwLatch, ref rwLockBuffer);
return writeInsertion(in key, in value, in info, in getResult, in overwrite, out retrievedValue,
exitOnTest, ref rwLockBuffer, ref rwLatch);
} else {
retrievedValue = default(Value);
return writeDeletion(in key, in info, in getResult, exitOnTest, ref rwLockBuffer, ref rwLatch);
}
} else {
rwLatch.ExitLatchChain(ref rwLockBuffer);
#if ConcurrentSortedDictionary_DEBUG
Test.Assert(!rwLatch.HoldingRootLock);
Test.Assert(ReferenceEquals(null, rwLockBuffer.peek()));
#endif
}
} finally {
#if ConcurrentSortedDictionary_DEBUG
Test.Assert(rwLockBuffer.peek() == null);
Test.Assert(!rwLatch.HoldingRootLock);
#endif
}
// Otherwise, try to acquire write access using a full write latch chain
// Note* forcing test to false
var writeLatchAccessType = accessType == LatchAccessType.insertTest ? LatchAccessType.insert : accessType;
writeLatchAccessType = accessType == LatchAccessType.deleteTest ? LatchAccessType.delete : accessType;
var writeLatch = new Latch<Key, Value>(writeLatchAccessType , this._rootLock, assumeLeafIsSafe: false);
var writeLockBuffer = new LockBuffer32<Key, Value>();
remainingMs = getRemainingMs(in startTime, in timeoutMs);
searchOptions = new SearchOptions(remainingMs, startTime: startTime);
getResult = ConcurrentKTreeNode<Key, Value>.TryGetValue(in key, out currentValue,
ref info, ref writeLatch, ref writeLockBuffer, this, searchOptions);
// Check if timed out...
if (getResult == ConcurrentTreeResult_Extended.timedOut) {
retrievedValue = default(Value);
return ConcurrentTreeResult_Extended.timedOut;
}
try {
#if ConcurrentSortedDictionary_DEBUG
info.node.assertWriterLockHeld();
#endif
if (writeLatch.isInsertAccess) {
tryUpdateDepth(info.depth, ref writeLatch, ref writeLockBuffer);
return writeInsertion(in key, in value, in info, in getResult, in overwrite, out retrievedValue,
false, ref writeLockBuffer, ref writeLatch);
} else {
retrievedValue = default(Value);
return writeDeletion(in key, in info, in getResult, false, ref writeLockBuffer, ref writeLatch);
}
} finally {
#if ConcurrentSortedDictionary_DEBUG
Test.Assert(writeLockBuffer.peek() == null);
Test.Assert(!writeLatch.HoldingRootLock);
#endif
}
}
private ConcurrentTreeResult_Extended writeInsertion<LockBuffer>(
in Key key,
in Value value,
in SearchResultInfo<Key, Value> info,
in ConcurrentTreeResult_Extended getResult,
in bool overwrite,
out Value retrievedValue,
in bool exitOnTest, // if exitOnTest is true, then this function should never perform a write
ref LockBuffer lockBuffer,
ref Latch<Key, Value> latch
) where LockBuffer: ILockBuffer<Key, Value> {
// If the vaue already exists...
if (getResult == ConcurrentTreeResult_Extended.success || exitOnTest) {
if (overwrite && !exitOnTest) {
info.node.SetValue(info.index, in key, in value);
retrievedValue = value;
latch.ExitLatchChain(ref lockBuffer);
#if ConcurrentSortedDictionary_DEBUG
Test.Assert(!latch.HoldingRootLock);
Test.Assert(ReferenceEquals(null, lockBuffer.peek()));
#endif
return ConcurrentTreeResult_Extended.success;
}
retrievedValue = info.node.GetValue(info.index).value;
latch.ExitLatchChain(ref lockBuffer);
#if ConcurrentSortedDictionary_DEBUG
Test.Assert(!latch.HoldingRootLock);
Test.Assert(ReferenceEquals(null, lockBuffer.peek()));
#endif
return ConcurrentTreeResult_Extended.alreadyExists;
}
info.node.sync_InsertAtThisNode(in key, in value, this, ref lockBuffer, ref latch);
// NOTE* tree is unlocked after sync_Insert
Interlocked.Increment(ref this._count); // increase count
retrievedValue = value;
return ConcurrentTreeResult_Extended.success;
}
private ConcurrentTreeResult_Extended writeDeletion<LockBuffer>(
in Key key,
in SearchResultInfo<Key, Value> info,
in ConcurrentTreeResult_Extended getResult,
in bool exitOnTest, // if exitOnTest is true, then this function should never perform a write
ref LockBuffer lockBuffer,
ref Latch<Key, Value> latch
) where LockBuffer: ILockBuffer<Key, Value> {
if (getResult == ConcurrentTreeResult_Extended.notFound || exitOnTest) {
latch.ExitLatchChain(ref lockBuffer);
#if ConcurrentSortedDictionary_DEBUG
Test.Assert(!latch.HoldingRootLock);
Test.Assert(ReferenceEquals(null, lockBuffer.peek()));
#endif
return ConcurrentTreeResult_Extended.notFound;
}
info.node.sync_DeleteAtThisNode(in key, this, ref lockBuffer, ref latch);
// NOTE* tree is unlocked after sync_delete
Interlocked.Decrement(ref this._count); // decrement count
return ConcurrentTreeResult_Extended.success;
}
/// <summary>
/// Remove a key-value pair from the tree.
/// </summary>
public RemoveResult TryRemove(in Key key, int timeoutMs) {
assertTimeoutArg(timeoutMs);
Value v = default(Value);
return ToRemoveResult(writeToTree(in key, in v, in timeoutMs, LatchAccessType.deleteTest, out v));
}
/// <summary>
/// Remove a key-value pair from the tree. Waits forever until mutex(s) are acquired.
/// </summary>
public bool TryRemove(in Key key) {
Value v = default(Value);
return ToRemoveResult(writeToTree(in key, in v, -1, LatchAccessType.deleteTest, out v)) == RemoveResult.success;
}
/// <summary>
/// Search for input key and outputs the value. Returns false if not found. Waits forever until search mutex(s) are acquired.
/// </summary>
public bool TryGetValue(in Key key, out Value value) {
return tryGetValue(in key, out value, -1) == SearchResult.success;
}
/// <summary>
/// Search for input key and outputs the value. Returns if it was successful.
/// </summary>
public SearchResult TryGetValue(in Key key, out Value value, in int timeoutMs) {
assertTimeoutArg(timeoutMs);
return tryGetValue(in key, out value, timeoutMs);
}
/// <summary>
/// Check if the input key is in this collection.
/// </summary>
public SearchResult ContainsKey(in Key key, in int timeoutMs) {
assertTimeoutArg(timeoutMs);
Value value;
return tryGetValue(in key, out value, in timeoutMs);
}
/// <summary>
/// Check if the input key is in this collection. Wait forever to acquire mutex(s)
/// </summary>
public bool ContainsKey(in Key key) {
Value value;
return tryGetValue(in key, out value, -1)== SearchResult.success;
}
/// <summary>
/// Search for input key and output the value.
/// </summary>
private SearchResult tryGetValue(in Key key, out Value value, in int timeoutMs = -1) {
if (!typeof(Key).IsValueType && ReferenceEquals(null, key)) {
throw new ArgumentException("Cannot have null key");
}
SearchResultInfo<Key, Value> searchInfo = default(SearchResultInfo<Key, Value>);
var searchOptions = new SearchOptions(timeoutMs);
var latch = new Latch<Key, Value> (LatchAccessType.read, this._rootLock);
var readLockBuffer = new LockBuffer2<Key, Value>();
var result = ConcurrentKTreeNode<Key, Value>.TryGetValue(in key, out value,
ref searchInfo, ref latch, ref readLockBuffer, this, searchOptions);
if (result == ConcurrentTreeResult_Extended.timedOut) {
return SearchResult.timedOut;
}
this._depth = searchInfo.depth; // Note* Int32 read/write is atomic
return result == ConcurrentTreeResult_Extended.success ?
SearchResult.success :
SearchResult.notFound;
}
public Value this[in Key key]
{
get {
Value value;
if (!this.TryGetValue(in key, out value)) {
throw new ArgumentException("Input key does not exist!");
}
return value;
}
set {
this.AddOrUpdate(in key, in value);
}
}
/// <summary>
/// Can be used to iterate though all items in the Dictionary with optional timeout and subtree depth.
/// </summary>
public IEnumerable<KeyValuePair<Key, Value>> Items(int itemTimeoutMs = -1) {
using (var it = GetEnumerator(itemTimeoutMs)) {
while (it.MoveNext()) {
yield return it.Current;
}
};
}
/// <summary>
/// Returns all items in the tree. Reversed ordering.
/// </summary>
/// <param name="itemTimeoutMs"> optional timeout. </param>
/// <returns></returns>
public IEnumerable<KeyValuePair<Key, Value>> Reversed(int itemTimeoutMs = -1) {
using (var it = GetEnumerator(itemTimeoutMs, reversed: true)) {
while (it.MoveNext()) {
yield return it.Current;
}
};
}
/// <summary>
/// Returns all items in the tree within the desired range. If start > stop then the iterator uses reverse iteration direction.
/// </summary>
/// <param name="startInclusive"> inclusive start iteration. </param>
/// <param name="endExclusive"> exclusive end iteration. </param>
/// <param name="itemTimeoutMs"> optional timeout. </param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public IEnumerable<KeyValuePair<Key, Value>> Range(Key startInclusive, Key endExclusive, int itemTimeoutMs = -1) {
int cmp = startInclusive.CompareTo(endExclusive);
if (cmp == 0) {
throw new ArgumentException("Iteration range start cannot equal end!");
}
bool reverse = cmp >= 0;
using (var it = GetEnumerator(startInclusive, true, endExclusive, true, itemTimeoutMs, reverse)) {
while (it.MoveNext()) {
yield return it.Current;
}
};
}
/// <summary>
/// Returns all items in the tree starting with the desired inclusive key.
/// </summary>
public IEnumerable<KeyValuePair<Key, Value>> StartingWith(Key startInclusive, bool reverse = false, int itemTimeoutMs = -1) {
using (var it = GetEnumerator(startInclusive, true, default, false, itemTimeoutMs, reverse)) {
while (it.MoveNext()) {
yield return it.Current;
}
};
}
/// <summary>
/// Returns all items in the tree ending with the desired exclusive key.
/// </summary>
public IEnumerable<KeyValuePair<Key, Value>> EndingWith(Key endExclusive, bool reverse = false, int itemTimeoutMs = -1) {
using (var it = GetEnumerator(default, false, endExclusive, true, itemTimeoutMs, reverse)) {
while (it.MoveNext()) {
yield return it.Current;
}
};
}
public IEnumerable<Key> Keys { get { foreach (var pair in this) { yield return pair.Key; } } }
public IEnumerable<Value> Values { get { foreach (var pair in this) { yield return pair.Value; } } }
public IEnumerator<KeyValuePair<Key, Value>> GetEnumerator() {
return GetEnumerator(-1, false);
}
public IEnumerator<KeyValuePair<Key, Value>> GetEnumerator(
int itemTimeoutMs = -1,
bool reversed = false
) {
return ConcurrentKTreeNode<Key, Value>.AllItems(this, itemTimeoutMs, reversed).GetEnumerator();
}
public IEnumerator<KeyValuePair<Key, Value>> GetEnumerator(
Key startInclusive = default,
bool useStartInclusive = false,
Key endExclusive = default,
bool useEndExclusive = false,
int itemTimeoutMs = -1,
bool reversed = false
) {
return ConcurrentKTreeNode<Key, Value>.AllItems(
this, itemTimeoutMs, reversed, startInclusive, endExclusive, useStartInclusive, useEndExclusive
).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return this.GetEnumerator();
}
private SearchResult minMaxSearch(out KeyValuePair<Key, Value> result, SearchType searchType, int timeoutMs = -1) {
result = default;
SearchResultInfo<Key, Value> searchInfo = default(SearchResultInfo<Key, Value>);
var searchOptions = new SearchOptions(timeoutMs, type: searchType);
var latch = new Latch<Key, Value>(LatchAccessType.read, this._rootLock, retainReaderLock: true);
var readLockBuffer = new LockBuffer2<Key, Value>();
try {
Value val;
var resultEx = ConcurrentKTreeNode<Key, Value>.TryGetValue(default, out val,
ref searchInfo, ref latch, ref readLockBuffer, this, searchOptions);
if (resultEx == ConcurrentTreeResult_Extended.timedOut) {
return SearchResult.timedOut;
} else if (resultEx == ConcurrentTreeResult_Extended.notFound) {
return SearchResult.notFound;
} else {
#if ConcurrentSortedDictionary_DEBUG
int version = searchInfo.node.assertLatchLock(ref latch, beginRead: true);
#endif
// We need to maintain a read latch so we can retrieve the key safely
var nodeValue = searchType == SearchType.findMin
? searchInfo.node.GetValue(0)
: searchInfo.node.GetValue(searchInfo.node.Count - 1);
result = new KeyValuePair<Key, Value>(nodeValue.key, nodeValue.value);
#if ConcurrentSortedDictionary_DEBUG
searchInfo.node.assertLatchLock(ref latch, version);
#endif
return SearchResult.success;
}
} finally {
// Release Latch before exiting
latch.ExitLatchChain(ref readLockBuffer);
}
}
public KeyValuePair<Key, Value> GetMinOrDefault(KeyValuePair<Key, Value> defaultValue = default, int timeoutMs = -1) {
KeyValuePair<Key, Value> result;
SearchResult searchResult = minMaxSearch(out result, SearchType.findMin, timeoutMs);
if (searchResult == SearchResult.success) {
return result;
}
return defaultValue;
}
public KeyValuePair<Key, Value> GetMaxOrDefault(KeyValuePair<Key, Value> defaultValue = default, int timeoutMs = -1) {
KeyValuePair<Key, Value> result;
SearchResult searchResult = minMaxSearch(out result, SearchType.findMax, timeoutMs);
if (searchResult == SearchResult.success) {
return result;
}
return defaultValue;
}
/// <summary>
/// Get the min value in the collection.
/// </summary>
public SearchResult TryPeekMin(out KeyValuePair<Key, Value> min, int timeoutMs = -1) {
return minMaxSearch(out min, SearchType.findMin, timeoutMs);
}
/// <summary>
/// Get the max value in the collection.
/// </summary>
public SearchResult TryPeekMax(out KeyValuePair<Key, Value> min, int timeoutMs = -1) {
return minMaxSearch(out min, SearchType.findMax, timeoutMs);
}
/// <summary>
/// Get the min value in the collection. Returns false if the collection is empty. Throws exception if timed out.
/// </summary>
public bool PeekMin(out KeyValuePair<Key, Value> min, int timeoutMs = -1) {
SearchResult result = minMaxSearch(out min, SearchType.findMin, timeoutMs);
if (result == SearchResult.timedOut) {
throw new TimeoutException();
}
return result == SearchResult.success;
}
/// <summary>
/// Get the max value in the collection. Returns false if the collection is empty. Throws exception if timed out.
/// </summary>
public bool PeekMax(out KeyValuePair<Key, Value> min, int timeoutMs = -1) {
SearchResult result = minMaxSearch(out min, SearchType.findMax, timeoutMs);
if (result == SearchResult.timedOut) {
throw new TimeoutException();
}
return result == SearchResult.success;
}
public void Clear() {
clear();
}
public bool Clear(int timeoutMs) {
assertTimeoutArg(timeoutMs);
return clear();
}
private bool clear(int timeoutMs = -1) {
// Try to enter the root lock
var latch = new Latch<Key, Value> (LatchAccessType.delete, this._rootLock, assumeLeafIsSafe: false);
if (!latch.TryEnterRootLock(timeoutMs)) {
return false;
}
try {
// Make a new root...
var newRoot = new ConcurrentKTreeNode<Key, Value>(_root.k, isLeaf: true);
this.setRoot(newRoot);
this._count = 0;
this._depth = 0;
return true;
} finally {
latch.ExitRootLock();
}
}
/// <summary>
/// Struct that contains meta data about the TryGetValue search attempt.
/// </summary>
private struct SearchResultInfo<K, V> where K : IComparable<K> {
/// <summary>
/// Index of found item. -1 if not found.
/// </summary>
public int index;
/// <summary>
/// Node that the search stopped at.
/// </summary>
public ConcurrentKTreeNode<K, V> node;
/// <summary>
/// Depth where search stopped
/// </summary>
public int depth;
/// <summary>
/// Next key of next node
/// </summary>
public K nextSubTreeKey;
/// <summary>
/// Is there a subtree after this one?
/// </summary>
public bool hasNextSubTree;
}
private enum SearchType {
search = 0,
findMin = 1,
findMax = 2
}
private struct SearchOptions {
private const int kDefaultMaxDepth = int.MaxValue - 1;
public readonly int timeoutMs;
public readonly int maxDepth;
public readonly long startTime;
public SearchType type;
public SearchOptions(in int timeoutMs = -1, in int maxDepth = kDefaultMaxDepth, in SearchType type = SearchType.search, in long startTime = -1) {
this.timeoutMs = timeoutMs; this.maxDepth = maxDepth; this.type = type;
this.startTime = startTime < 0 ? DateTimeOffset.Now.ToUnixTimeMilliseconds() : startTime;
}
public void assertValid(bool isReadAccess) {
if (this.maxDepth != kDefaultMaxDepth && !isReadAccess)
throw new ArgumentException("Can only set maxDepth for read access");
if (maxDepth > kDefaultMaxDepth || maxDepth < 0)
throw new ArgumentException("Invalid maxDepth specified");
}
}
/// <summary>
/// Key-Value pair that is used to store all items in the tree.
/// </summary>
private struct NodeData<K, V> where K: IComparable<K> {
public readonly V value;
public readonly K key;
public NodeData(in K key, in V value) {
this.value = value;
this.key = key;
}
}
private enum ConcurrentTreeResult_Extended {
success = 0,
notFound = 1,
timedOut = 2,
alreadyExists = 3,
notSafeToUpdateLeaf = 4
}
private enum LatchAccessType {
read = 0,
insert = 1,
delete = 2,
insertTest = 3,
deleteTest = 4
}
private enum LatchAccessResult {
timedOut = 0,
acquired = 1,
notSafeToUpdateLeaf = 2,
// Test Result.. This is returned when it is not safe to update the leaf
// but we want to retain the lock on the leaf for the purpose of testing if the
// desired key is present
notSafeToUpdateLeafTest = 3
}
private interface ILockBuffer<K, V> where K: IComparable<K> {
public ConcurrentKTreeNode<K, V> peek();
public void push(in ConcurrentKTreeNode<K, V> node);
public ConcurrentKTreeNode<K, V> pop();
public ConcurrentKTreeNode<K, V> peekParent();
}
private struct LockBuffer2<K, V> : ILockBuffer<K, V> where K: IComparable<K> {
public ConcurrentKTreeNode<K, V> peek() {
if (!ReferenceEquals(null, r1)) return r1;
else return r0;
}
public ConcurrentKTreeNode<K, V> peekParent() {
if (!ReferenceEquals(null, r1)) return r0;
return null;
}
public void push(in ConcurrentKTreeNode<K, V> node) {
if (ReferenceEquals(null, r0)) r0 = node;
else if (ReferenceEquals(null, r1)) r1 = node;
else throw new ArgumentException("Lock stack is full");
}
public ConcurrentKTreeNode<K, V> pop() {
//Note* pop returns null on empty, this is intentional
// See Latch.ExitLatchChain- it will just iterate until pop() returns null
if (!ReferenceEquals(null, r1)) {
var result = r1;
r1 = null;
return result;
} else {
var result = r0;
r0 = null;
return result;
}
}
private ConcurrentKTreeNode<K, V> r0; private ConcurrentKTreeNode<K, V> r1;
}
// Doing this nonsense because c# doesn't allow stacalloc of reference type arrays.
// -And don't want to force users to use unsafe if they arent compiling with it.
// Another alternative is to create a pool<buffers> or linked list nodes-
// but this would potentially create unexpected memory usage by this data structure.
// This struct should be 256 bytes and is used whenever a write forces changing the tree structure.
private struct LockBuffer32<K, V> : ILockBuffer<K, V> where K: IComparable<K> {
public ConcurrentKTreeNode<K, V> peek() {
if (this.Count <= 0)
return null;
return get(this.Count - 1);
}
public ConcurrentKTreeNode<K, V> peekParent() {
if (this.Count <= 1)
return null;
return get(this.Count - 2);
}
public int Count { get; private set; }
public void push(in ConcurrentKTreeNode<K, V> node) {
if (this.Count >= 32)
throw new ArgumentException("Cannot push, reach lock buffer limit");
set(this.Count, in node);
this.Count++;
}
public ConcurrentKTreeNode<K, V> pop() {
//Note* pop returns null on empty, this is intentional
if (this.Count <= 0)
return null;
var topNode = get(this.Count - 1);
set(this.Count - 1, null);
this.Count--;
return topNode;
}
private ConcurrentKTreeNode<K, V> r0; private ConcurrentKTreeNode<K, V> r1; private ConcurrentKTreeNode<K, V> r2; private ConcurrentKTreeNode<K, V> r3;
private ConcurrentKTreeNode<K, V> r4; private ConcurrentKTreeNode<K, V> r5; private ConcurrentKTreeNode<K, V> r6; private ConcurrentKTreeNode<K, V> r7;
private ConcurrentKTreeNode<K, V> r8; private ConcurrentKTreeNode<K, V> r9; private ConcurrentKTreeNode<K, V> r10; private ConcurrentKTreeNode<K, V> r11;
private ConcurrentKTreeNode<K, V> r12; private ConcurrentKTreeNode<K, V> r13; private ConcurrentKTreeNode<K, V> r14; private ConcurrentKTreeNode<K, V> r15;
private ConcurrentKTreeNode<K, V> r16; private ConcurrentKTreeNode<K, V> r17; private ConcurrentKTreeNode<K, V> r18; private ConcurrentKTreeNode<K, V> r19;
private ConcurrentKTreeNode<K, V> r20; private ConcurrentKTreeNode<K, V> r21; private ConcurrentKTreeNode<K, V> r22; private ConcurrentKTreeNode<K, V> r23;
private ConcurrentKTreeNode<K, V> r24; private ConcurrentKTreeNode<K, V> r25; private ConcurrentKTreeNode<K, V> r26; private ConcurrentKTreeNode<K, V> r27;
private ConcurrentKTreeNode<K, V> r28; private ConcurrentKTreeNode<K, V> r29; private ConcurrentKTreeNode<K, V> r30; private ConcurrentKTreeNode<K, V> r31;
private void set(in int i, in ConcurrentKTreeNode<K, V> value) {
switch (i) {
case 0: this.r0 = value; return; case 1: this.r1 = value; return; case 2: this.r2 = value; return; case 3: this.r3 = value; return;
case 4: this.r4 = value; return; case 5: this.r5 = value; return; case 6: this.r6 = value; return; case 7: this.r7 = value; return;
case 8: this.r8 = value; return; case 9: this.r9 = value; return; case 10: this.r10 = value; return; case 11: this.r11 = value; return;
case 12: this.r12 = value; return; case 13: this.r13 = value; return; case 14: this.r14 = value; return; case 15: this.r15 = value; return;
case 16: this.r16 = value; return; case 17: this.r17 = value; return; case 18: this.r18 = value; return; case 19: this.r19 = value; return;
case 20: this.r20 = value; return; case 21: this.r21 = value; return; case 22: this.r22 = value; return; case 23: this.r23 = value; return;
case 24: this.r24 = value; return; case 25: this.r25 = value; return; case 26: this.r26 = value; return; case 27: this.r27 = value; return;
case 28: this.r28 = value; return; case 29: this.r29 = value; return; case 30: this.r30 = value; return; case 31: this.r31 = value; return;
}
}
private ConcurrentKTreeNode<K, V> get(in int i) {
switch (i) {
case 0: return this.r0; case 1: return this.r1; case 2: return this.r2; case 3: return this.r3;
case 4: return this.r4; case 5: return this.r5; case 6: return this.r6; case 7: return this.r7;
case 8: return this.r8; case 9: return this.r9; case 10: return this.r10; case 11: return this.r11;
case 12: return this.r12; case 13: return this.r13; case 14: return this.r14; case 15: return this.r15;
case 16: return this.r16; case 17: return this.r17; case 18: return this.r18; case 19: return this.r19;
case 20: return this.r20; case 21: return this.r21; case 22: return this.r22; case 23: return this.r23;
case 24: return this.r24; case 25: return this.r25; case 26: return this.r26; case 27: return this.r27;
case 28: return this.r28; case 29: return this.r29; case 30: return this.r30; case 31: return this.r31;
default: throw new IndexOutOfRangeException();
}
}
}
private struct Latch<K, V> where K : IComparable<K> {
/// <summary>
/// if 'true', write operations will acquire read locks all the way to the leaf- and then acquire
/// a write lock only on the leaf. if 'false' then write locks will be used to traverse down the
/// while latching.
/// </summary>
public readonly bool assumeLeafIsSafe;
/// <summary>
/// type of latch
/// </summary>
private readonly LatchAccessType accessType;
/// <summary>
/// Retain the reader lock on the found node after finishing a tree search?
/// </summary>
public readonly bool retainReaderLock;
private ReaderWriterLockSlim _rootLock;
public bool isInsertAccess { get { return this.accessType == LatchAccessType.insert || this.accessType == LatchAccessType.insertTest; } }
public bool isDeleteAccess { get { return this.accessType == LatchAccessType.delete || this.accessType == LatchAccessType.deleteTest; } }
public bool isReadAccess { get { return this.accessType == LatchAccessType.read; } }
public bool TryEnterRootLock(int timeoutMs = -1) {
if (this.isReadAccess || this.assumeLeafIsSafe) {
return this._rootLock.TryEnterReadLock(timeoutMs);
} else {
return this._rootLock.TryEnterWriteLock(timeoutMs);
}
}
/// <summary>
/// exits the rootLock or does nothing if it was already exited.
/// </summary>
public void ExitRootLock() {
if (!ReferenceEquals(null, this._rootLock)) {
if (this.isReadAccess || this.assumeLeafIsSafe) {
this._rootLock.ExitReadLock();
} else {
this._rootLock.ExitWriteLock();
}
this._rootLock = null;
}
}
#if ConcurrentSortedDictionary_DEBUG
public bool HoldingRootLock { get { return !ReferenceEquals(null, this._rootLock); } }
#endif
/// <summary>
/// Exit the latch at this level and every parent including the rootLock
/// </summary>
public void ExitLatchChain<LockBuffer>(ref LockBuffer lockBuffer) where LockBuffer : ILockBuffer<K, V> {
ConcurrentKTreeNode<K, V> node = lockBuffer.pop();