/
ReaderWriterLockSlim.cs
1657 lines (1413 loc) · 61.9 KB
/
ReaderWriterLockSlim.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics; // for TraceInformation
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Threading
{
public enum LockRecursionPolicy
{
NoRecursion = 0,
SupportsRecursion = 1,
}
//
// ReaderWriterCount tracks how many of each kind of lock is held by each thread.
// We keep a linked list for each thread, attached to a ThreadStatic field.
// These are reused wherever possible, so that a given thread will only
// allocate N of these, where N is the maximum number of locks held simultaneously
// by that thread.
//
internal sealed class ReaderWriterCount
{
// Which lock does this object belong to? This is a numeric ID for two reasons:
// 1) We don't want this field to keep the lock object alive, and a WeakReference would
// be too expensive.
// 2) Setting the value of a long is faster than setting the value of a reference.
// The "hot" paths in ReaderWriterLockSlim are short enough that this actually
// matters.
public long lockID;
// How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
public int readercount;
// Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
// But we have to have the fields on every ReaderWriterCount instance, because
// we reuse it for different locks.
public int writercount;
public int upgradecount;
// Next RWC in this thread's list.
public ReaderWriterCount? next;
}
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
/// efficient. In particular only 1 interlocked operation is taken for any lock
/// operation (we use spin locks to achieve this). The spin lock is never held
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
/// </summary>
public class ReaderWriterLockSlim : IDisposable
{
// Specifying if the lock can be reacquired recursively.
private readonly bool _fIsReentrant;
// Lock specification for _spinLock: This lock protects exactly the local fields associated with this
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
// the events that are raised by this lock (eg writeEvent, readEvent upgradeEvent).
private SpinLock _spinLock;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
private uint _numUpgradeWaiters;
private WaiterStates _waiterStates;
private int _upgradeLockOwnerId;
private int _writeLockOwnerId;
// conditions we wait on.
private EventWaitHandle? _writeEvent; // threads waiting to acquire a write lock go here.
private EventWaitHandle? _readEvent; // threads waiting to acquire a read lock go here (will be released in bulk)
private EventWaitHandle? _upgradeEvent; // thread waiting to acquire the upgrade lock
private EventWaitHandle? _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
// Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
// without holding a reference to it.
private static long s_nextLockID;
private readonly long _lockID;
// See comments on ReaderWriterCount.
[ThreadStatic]
private static ReaderWriterCount? t_rwc;
private bool _fUpgradeThreadHoldingRead;
private const int MaxSpinCount = 20;
// The uint, that contains info like if the writer lock is held, num of
// readers etc.
private uint _owners;
// Various R/W masks
// Note:
// The Uint is divided as follows:
//
// Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
// Dividing the uint, allows to vastly simplify logic for checking if a
// reader should go in etc. Setting the writer bit will automatically
// make the value of the uint much larger than the max num of readers
// allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
// The max readers is actually one less then its theoretical max.
// This is done in order to prevent reader count overflows. If the reader
// count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
private bool _fDisposed;
private void InitializeThreadCounts()
{
_upgradeLockOwnerId = -1;
_writeLockOwnerId = -1;
}
public ReaderWriterLockSlim()
: this(LockRecursionPolicy.NoRecursion)
{
}
public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
{
if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
{
_fIsReentrant = true;
}
InitializeThreadCounts();
_waiterStates = WaiterStates.NoWaiters;
_lockID = Interlocked.Increment(ref s_nextLockID);
}
private bool HasNoWaiters
{
get
{
#if DEBUG
Debug.Assert(_spinLock.IsHeld);
#endif
return (_waiterStates & WaiterStates.NoWaiters) != WaiterStates.None;
}
set
{
#if DEBUG
Debug.Assert(_spinLock.IsHeld);
#endif
if (value)
{
_waiterStates |= WaiterStates.NoWaiters;
}
else
{
_waiterStates &= ~WaiterStates.NoWaiters;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
if (rwc.lockID == 0)
return true;
else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
return true;
else
return false;
}
private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
{
return lrwc.lockID != _lockID;
}
/// <summary>
/// This routine retrieves/sets the per-thread counts needed to enforce the
/// various rules related to acquiring the lock.
///
/// DontAllocate is set to true if the caller just wants to get an existing
/// entry for this thread, but doesn't want to add one if an existing one
/// could not be found.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ReaderWriterCount? GetThreadRWCount(bool dontAllocate)
{
ReaderWriterCount? rwc = t_rwc;
ReaderWriterCount? empty = null;
while (rwc != null)
{
if (rwc.lockID == _lockID)
return rwc;
if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
empty = rwc;
rwc = rwc.next;
}
if (dontAllocate)
return null;
if (empty == null)
{
empty = new ReaderWriterCount();
empty.next = t_rwc;
t_rwc = empty;
}
empty.lockID = _lockID;
return empty;
}
public void EnterReadLock()
{
TryEnterReadLock(-1);
}
//
// Common timeout support
//
private struct TimeoutTracker
{
private readonly int _total;
private readonly int _start;
public TimeoutTracker(TimeSpan timeout)
{
long ltm = (long)timeout.TotalMilliseconds;
if (ltm < -1 || ltm > (long)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout));
_total = (int)ltm;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public TimeoutTracker(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
_total = millisecondsTimeout;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public int RemainingMilliseconds
{
get
{
if (_total == -1 || _total == 0)
return _total;
int elapsed = Environment.TickCount - _start;
// elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
if (elapsed < 0 || elapsed >= _total)
return 0;
return _total - elapsed;
}
}
public bool IsExpired => RemainingMilliseconds == 0;
}
public bool TryEnterReadLock(TimeSpan timeout)
{
return TryEnterReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterReadLock(TimeoutTracker timeout)
{
return TryEnterReadLockCore(timeout);
}
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
ReaderWriterCount lrwc;
int id = Environment.CurrentManagedThreadId;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
// Check for AW->AR
throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
}
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
lrwc = GetThreadRWCount(dontAllocate: false)!;
// Check if the reader lock is already acquired. Note, we could
// check the presence of a reader by not allocating rwc (But that
// would lead to two lookups in the common case. It's better to keep
// a count in the structure).
if (lrwc.readercount > 0)
{
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
// The upgrade lock is already held.
// Update the global read counts and exit.
lrwc.readercount++;
_owners++;
_spinLock.Exit();
return true;
}
}
else
{
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
lrwc = GetThreadRWCount(dontAllocate: false)!;
if (lrwc.readercount > 0)
{
lrwc.readercount++;
_spinLock.Exit();
return true;
}
else if (id == _upgradeLockOwnerId)
{
// The upgrade lock is already held.
// Update the global read counts and exit.
lrwc.readercount++;
_owners++;
_spinLock.Exit();
_fUpgradeThreadHoldingRead = true;
return true;
}
else if (id == _writeLockOwnerId)
{
// The write lock is already held.
// Update global read counts here,
lrwc.readercount++;
_owners++;
_spinLock.Exit();
return true;
}
}
bool retVal = true;
int spinCount = 0;
while (true)
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
if (_owners < MAX_READER)
{
// Good case, there is no contention, we are basically done
_owners++; // Indicate we have another reader
lrwc.readercount++;
break;
}
if (timeout.IsExpired)
{
_spinLock.Exit();
return false;
}
if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
{
_spinLock.Exit();
spinCount++;
SpinWait(spinCount);
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
// The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_readEvent == null) // Create the needed event
{
LazyCreateEvent(ref _readEvent, EnterLockType.Read);
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, EnterLockType.Read);
if (!retVal)
{
return false;
}
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
}
_spinLock.Exit();
return retVal;
}
public void EnterWriteLock()
{
TryEnterWriteLock(-1);
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
return TryEnterWriteLock(new TimeoutTracker(timeout));
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterWriteLock(TimeoutTracker timeout)
{
return TryEnterWriteLockCore(timeout);
}
private bool TryEnterWriteLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount? lrwc;
bool upgradingToWrite = false;
if (!_fIsReentrant)
{
EnterSpinLockReason enterMyLockReason;
if (id == _writeLockOwnerId)
{
// Check for AW->AW
throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
// AU->AW case is allowed once.
upgradingToWrite = true;
enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
}
else
{
enterMyLockReason = EnterSpinLockReason.EnterWrite;
}
_spinLock.Enter(enterMyLockReason);
lrwc = GetThreadRWCount(dontAllocate: true);
// Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
else
{
EnterSpinLockReason enterMyLockReason;
if (id == _writeLockOwnerId)
{
enterMyLockReason = EnterSpinLockReason.EnterRecursiveWrite;
}
else if (id == _upgradeLockOwnerId)
{
enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
}
else
{
enterMyLockReason = EnterSpinLockReason.EnterWrite;
}
_spinLock.Enter(enterMyLockReason);
lrwc = GetThreadRWCount(dontAllocate: false)!;
if (id == _writeLockOwnerId)
{
lrwc.writercount++;
_spinLock.Exit();
return true;
}
else if (id == _upgradeLockOwnerId)
{
upgradingToWrite = true;
}
else if (lrwc.readercount > 0)
{
// Write locks may not be acquired if only read locks have been
// acquired.
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
bool retVal;
int spinCount = 0;
while (true)
{
if (IsWriterAcquired())
{
// Good case, there is no contention, we are basically done
SetWriterAcquired();
break;
}
// Check if there is just one upgrader, and no readers.
// Assumption: Only one thread can have the upgrade lock, so the
// following check will fail for all other threads that may sneak in
// when the upgrading thread is waiting.
if (upgradingToWrite)
{
uint readercount = GetNumReaders();
if (readercount == 1)
{
// Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
else if (readercount == 2)
{
if (lrwc != null)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
if (lrwc.readercount > 0)
{
// This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(_fIsReentrant);
Debug.Assert(_fUpgradeThreadHoldingRead);
// Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
}
}
}
if (timeout.IsExpired)
{
_spinLock.Exit();
return false;
}
if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyWrite(upgradingToWrite))
{
_spinLock.Exit();
spinCount++;
SpinWait(spinCount);
_spinLock.Enter(upgradingToWrite ? EnterSpinLockReason.UpgradeToWrite : EnterSpinLockReason.EnterWrite);
continue;
}
if (upgradingToWrite)
{
if (_waitUpgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _waitUpgradeEvent, EnterLockType.UpgradeToWrite);
continue; // since we left the lock, start over.
}
Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, EnterLockType.UpgradeToWrite);
// The lock is not held in case of failure.
if (!retVal)
return false;
}
else
{
// Drat, we need to wait. Mark that we have waiters and wait.
if (_writeEvent == null) // create the needed event.
{
LazyCreateEvent(ref _writeEvent, EnterLockType.Write);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, EnterLockType.Write);
// The lock is not held in case of failure.
if (!retVal)
return false;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0);
if (_fIsReentrant)
{
Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method");
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
lrwc.writercount++;
}
_spinLock.Exit();
_writeLockOwnerId = id;
return true;
}
public void EnterUpgradeableReadLock()
{
TryEnterUpgradeableReadLock(-1);
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
{
return TryEnterUpgradeableReadLockCore(timeout);
}
private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount? lrwc;
if (!_fIsReentrant)
{
if (id == _upgradeLockOwnerId)
{
// Check for AU->AU
throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
}
else if (id == _writeLockOwnerId)
{
// Check for AU->AW
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
}
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
lrwc = GetThreadRWCount(dontAllocate: true);
// Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
else
{
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
lrwc = GetThreadRWCount(dontAllocate: false)!;
if (id == _upgradeLockOwnerId)
{
lrwc.upgradecount++;
_spinLock.Exit();
return true;
}
else if (id == _writeLockOwnerId)
{
// Write lock is already held, Just update the global state
// to show presence of upgrader.
Debug.Assert((_owners & WRITER_HELD) > 0);
_owners++;
_upgradeLockOwnerId = id;
lrwc.upgradecount++;
if (lrwc.readercount > 0)
_fUpgradeThreadHoldingRead = true;
_spinLock.Exit();
return true;
}
else if (lrwc.readercount > 0)
{
// Upgrade locks may not be acquired if only read locks have been
// acquired.
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
int spinCount = 0;
while (true)
{
// Once an upgrade lock is taken, it's like having a reader lock held
// until upgrade or downgrade operations are performed.
if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
{
_owners++;
_upgradeLockOwnerId = id;
break;
}
if (timeout.IsExpired)
{
_spinLock.Exit();
return false;
}
if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
{
_spinLock.Exit();
spinCount++;
SpinWait(spinCount);
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_upgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _upgradeEvent, EnterLockType.UpgradeableRead);
continue; // since we left the lock, start over.
}
// Only one thread with the upgrade lock held can proceed.
bool retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, EnterLockType.UpgradeableRead);
if (!retVal)
return false;
}
if (_fIsReentrant)
{
// The lock may have been dropped getting here, so make a quick check to see whether some other
// thread did not grab the entry.
Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method");
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
lrwc.upgradecount++;
}
_spinLock.Exit();
return true;
}
public void ExitReadLock()
{
_spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true);
if (lrwc == null || lrwc.readercount < 1)
{
// You have to be holding the read lock to make this call.
_spinLock.Exit();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
}
if (_fIsReentrant)
{
if (lrwc.readercount > 1)
{
lrwc.readercount--;
_spinLock.Exit();
return;
}
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
{
_fUpgradeThreadHoldingRead = false;
}
}
Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--_owners;
Debug.Assert(lrwc.readercount == 1);
lrwc.readercount--;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitWriteLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
{
// You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
_spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
}
else
{
_spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
lrwc = GetThreadRWCount(dontAllocate: false)!;
if (lrwc == null)
{
_spinLock.Exit();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
if (lrwc.writercount < 1)
{
_spinLock.Exit();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
lrwc.writercount--;
if (lrwc.writercount > 0)
{
_spinLock.Exit();
return;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
ClearWriterAcquired();
_writeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitUpgradeableReadLock()
{
ReaderWriterCount? lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
{
// You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
_spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
}
else
{
_spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
lrwc = GetThreadRWCount(dontAllocate: true);
if (lrwc == null)
{
_spinLock.Exit();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
if (lrwc.upgradecount < 1)
{
_spinLock.Exit();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
lrwc.upgradecount--;
if (lrwc.upgradecount > 0)
{
_spinLock.Exit();
return;
}
_fUpgradeThreadHoldingRead = false;
}
_owners--;
_upgradeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
/// <summary>
/// A routine for lazily creating a event outside the lock (so if errors
/// happen they are outside the lock and that we don't do much work
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent([NotNull] ref EventWaitHandle? waitEvent, EnterLockType enterLockType)
{
#if DEBUG
Debug.Assert(_spinLock.IsHeld);
Debug.Assert(waitEvent == null);
#endif
_spinLock.Exit();
var newEvent =
new EventWaitHandle(
false,
enterLockType == EnterLockType.Read ? EventResetMode.ManualReset : EventResetMode.AutoReset);
EnterSpinLockReason enterMyLockReason;
switch (enterLockType)
{
case EnterLockType.Read:
case EnterLockType.UpgradeableRead:
enterMyLockReason = EnterSpinLockReason.EnterAnyRead | EnterSpinLockReason.Wait;
break;
case EnterLockType.Write:
enterMyLockReason = EnterSpinLockReason.EnterWrite | EnterSpinLockReason.Wait;
break;
default:
Debug.Assert(enterLockType == EnterLockType.UpgradeToWrite);
enterMyLockReason = EnterSpinLockReason.UpgradeToWrite | EnterSpinLockReason.Wait;
break;
}
_spinLock.Enter(enterMyLockReason);
if (waitEvent == null) // maybe someone snuck in.
waitEvent = newEvent;
else
newEvent.Dispose();
}
/// <summary>
/// Waits on 'waitEvent' with a timeout
/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
/// </summary>
private bool WaitOnEvent(
EventWaitHandle waitEvent,
ref uint numWaiters,
TimeoutTracker timeout,
EnterLockType enterLockType)
{
#if DEBUG
Debug.Assert(_spinLock.IsHeld);
#endif
WaiterStates waiterSignaledState = WaiterStates.None;
EnterSpinLockReason enterMyLockReason;
switch (enterLockType)
{
case EnterLockType.UpgradeableRead:
waiterSignaledState = WaiterStates.UpgradeableReadWaiterSignaled;
goto case EnterLockType.Read;
case EnterLockType.Read:
enterMyLockReason = EnterSpinLockReason.EnterAnyRead;
break;
case EnterLockType.Write:
waiterSignaledState = WaiterStates.WriteWaiterSignaled;
enterMyLockReason = EnterSpinLockReason.EnterWrite;
break;
default:
Debug.Assert(enterLockType == EnterLockType.UpgradeToWrite);
enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
break;
}
// It was not possible to acquire the RW lock because some other thread was holding some type of lock. The other
// thread, when it releases its lock, will wake appropriate waiters. Along with resetting the wait event, clear the
// waiter signaled bit for this type of waiter if applicable, to indicate that a waiter of this type is no longer
// signaled.
//
// If the waiter signaled bit is not updated upon event reset, the following scenario would lead to deadlock:
// - Thread T0 signals the write waiter event or the upgradeable read waiter event to wake a waiter
// - There are no threads waiting on the event, but T1 is in WaitOnEvent() after exiting the spin lock and before
// actually waiting on the event (that is, it's recorded that there is one waiter for the event). It remains in
// this region for a while, in the repro case it typically gets context-switched out.
// - T2 acquires the RW lock in some fashion that blocks T0 or T3 from acquiring the RW lock
// - T0 or T3 fails to acquire the RW lock enough times for it to enter WaitOnEvent for the same event as T1
// - T0 or T3 resets the event
// - T2 releases the RW lock and does not wake a waiter because the reset at the previous step lost a signal but
// _waiterStates was not updated to reflect that
// - T1 and other threads begin waiting on the event, but there's no longer any thread that would wake them
if (waiterSignaledState != WaiterStates.None && (_waiterStates & waiterSignaledState) != WaiterStates.None)
{