Repository navigation
Expand file tree
/
Copy pathLock.cs
More file actions
1275 lines (1109 loc) · 56.9 KB
/
Copy pathLock.cs
File metadata and controls
1275 lines (1109 loc) · 56.9 KB
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;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
namespace System.Threading
{
/// <summary>
/// Provides a way to get mutual exclusion in regions of code between different threads. A lock may be held by one thread at
/// a time.
/// </summary>
/// <remarks>
/// Threads that cannot immediately enter the lock may wait for the lock to be exited or until a specified timeout. A thread
/// that holds a lock may enter the lock repeatedly without exiting it, such as recursively, in which case the thread should
/// eventually exit the lock the same number of times to fully exit the lock and allow other threads to enter the lock.
/// </remarks>
public sealed partial class Lock
{
private const short DefaultMaxSpinCount = 22;
private const short DefaultAdaptiveSpinPeriod = 100;
private const short SpinSleep0Threshold = 10;
private const ushort MaxDurationMsForPreemptingWaiters = 100;
private static long s_contentionCount;
// The field's type is not ThreadId to try to retain the relative order of fields of intrinsic types. The type system
// appears to place struct fields after fields of other types, in which case there can be a greater chance that
// _owningThreadId is not in the same cache line as _state.
#if TARGET_OSX && !NATIVEAOT
private ulong _owningThreadId;
#else
private uint _owningThreadId;
#endif
private uint _state; // see State for layout
private uint _recursionCount;
// This field serves a few purposes currently:
// - When positive, it indicates the number of spin-wait iterations that most threads would do upon contention
// - When zero, it indicates that spin-waiting is to be attempted by a thread to test if it is successful
// - When negative, it serves as a rough counter for contentions that would increment it towards zero
//
// See references to this field and "AdaptiveSpin" in TryEnterSlow for more information.
private short _spinCount;
private ushort _waiterStartTimeMs;
private AutoResetEvent? _waitEvent;
#if NATIVEAOT // The method needs to be public in NativeAOT so that other private libraries can access it
public Lock(bool useTrivialWaits)
#else
internal Lock(bool useTrivialWaits)
#endif
: this()
{
State.InitializeUseTrivialWaits(this, useTrivialWaits);
}
/// <summary>
/// Enters the lock. Once the method returns, the calling thread would be the only thread that holds the lock.
/// </summary>
/// <remarks>
/// If the lock cannot be entered immediately, the calling thread waits for the lock to be exited. If the lock is
/// already held by the calling thread, the lock is entered again. The calling thread should exit the lock as many times
/// as it had entered the lock to fully exit the lock and allow other threads to enter the lock.
/// </remarks>
/// <exception cref="LockRecursionException">
/// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high
/// enough that it would typically not be reached when the lock is used properly.
/// </exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Enter()
{
ThreadId currentThreadId = TryEnter_Inlined(timeoutMs: -1);
Debug.Assert(currentThreadId.IsInitialized);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private ThreadId EnterAndGetCurrentThreadId()
{
ThreadId currentThreadId = TryEnter_Inlined(timeoutMs: -1);
Debug.Assert(currentThreadId.IsInitialized);
Debug.Assert(currentThreadId.Id == _owningThreadId);
return currentThreadId;
}
/// <summary>
/// Enters the lock and returns a <see cref="Scope"/> that may be disposed to exit the lock. Once the method returns,
/// the calling thread would be the only thread that holds the lock. This method is intended to be used along with a
/// language construct that would automatically dispose the <see cref="Scope"/>, such as with the C# <code>using</code>
/// statement.
/// </summary>
/// <returns>
/// A <see cref="Scope"/> that may be disposed to exit the lock.
/// </returns>
/// <remarks>
/// If the lock cannot be entered immediately, the calling thread waits for the lock to be exited. If the lock is
/// already held by the calling thread, the lock is entered again. The calling thread should exit the lock, such as by
/// disposing the returned <see cref="Scope"/>, as many times as it had entered the lock to fully exit the lock and
/// allow other threads to enter the lock.
/// </remarks>
/// <exception cref="LockRecursionException">
/// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high
/// enough that it would typically not be reached when the lock is used properly.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Scope EnterScope() => new Scope(this, EnterAndGetCurrentThreadId());
/// <summary>
/// A disposable structure that is returned by <see cref="EnterScope()"/>, which when disposed, exits the lock.
/// </summary>
public ref struct Scope
{
private Lock? _lockObj;
private ThreadId _currentThreadId;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Scope(Lock lockObj, ThreadId currentThreadId)
{
_lockObj = lockObj;
_currentThreadId = currentThreadId;
}
/// <summary>
/// Exits the lock.
/// </summary>
/// <remarks>
/// If the calling thread holds the lock multiple times, such as recursively, the lock is exited only once. The
/// calling thread should ensure that each enter is matched with an exit.
/// </remarks>
/// <exception cref="SynchronizationLockException">
/// The calling thread does not hold the lock.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
Lock? lockObj = _lockObj;
if (lockObj is not null)
{
_lockObj = null;
lockObj.Exit(_currentThreadId);
}
}
}
/// <summary>
/// Tries to enter the lock without waiting. If the lock is entered, the calling thread would be the only thread that
/// holds the lock.
/// </summary>
/// <returns>
/// <code>true</code> if the lock was entered, <code>false</code> otherwise.
/// </returns>
/// <remarks>
/// If the lock cannot be entered immediately, the method returns <code>false</code>. If the lock is already held by the
/// calling thread, the lock is entered again. The calling thread should exit the lock as many times as it had entered
/// the lock to fully exit the lock and allow other threads to enter the lock.
/// </remarks>
/// <exception cref="LockRecursionException">
/// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high
/// enough that it would typically not be reached when the lock is used properly.
/// </exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public bool TryEnter() => TryEnter_Inlined(timeoutMs: 0).IsInitialized;
/// <summary>
/// Tries to enter the lock, waiting for roughly the specified duration. If the lock is entered, the calling thread
/// would be the only thread that holds the lock.
/// </summary>
/// <param name="millisecondsTimeout">
/// The rough duration in milliseconds for which the method will wait if the lock is not available. A value of
/// <code>0</code> specifies that the method should not wait, and a value of <see cref="Timeout.Infinite"/> or
/// <code>-1</code> specifies that the method should wait indefinitely until the lock is entered.
/// </param>
/// <returns>
/// <code>true</code> if the lock was entered, <code>false</code> otherwise.
/// </returns>
/// <remarks>
/// If the lock cannot be entered immediately, the calling thread waits for roughly the specified duration for the lock
/// to be exited. If the lock is already held by the calling thread, the lock is entered again. The calling thread
/// should exit the lock as many times as it had entered the lock to fully exit the lock and allow other threads to
/// enter the lock.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is less than <code>-1</code>.
/// </exception>
/// <exception cref="LockRecursionException">
/// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high
/// enough that it would typically not be reached when the lock is used properly.
/// </exception>
public bool TryEnter(int millisecondsTimeout)
{
ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1);
return TryEnter_Outlined(millisecondsTimeout);
}
/// <summary>
/// Tries to enter the lock, waiting for roughly the specified duration. If the lock is entered, the calling thread
/// would be the only thread that holds the lock.
/// </summary>
/// <param name="timeout">
/// The rough duration for which the method will wait if the lock is not available. The timeout is converted to a number
/// of milliseconds by casting <see cref="TimeSpan.TotalMilliseconds"/> of the timeout to an integer value. A value
/// representing <code>0</code> milliseconds specifies that the method should not wait, and a value representing
/// <see cref="Timeout.Infinite"/> or <code>-1</code> milliseconds specifies that the method should wait indefinitely
/// until the lock is entered.
/// </param>
/// <returns>
/// <code>true</code> if the lock was entered, <code>false</code> otherwise.
/// </returns>
/// <remarks>
/// If the lock cannot be entered immediately, the calling thread waits for roughly the specified duration for the lock
/// to be exited. If the lock is already held by the calling thread, the lock is entered again. The calling thread
/// should exit the lock as many times as it had entered the lock to fully exit the lock and allow other threads to
/// enter the lock.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="timeout"/>, after its conversion to an integer millisecond value, represents a value that is less
/// than <code>-1</code> milliseconds or greater than <see cref="int.MaxValue"/> milliseconds.
/// </exception>
/// <exception cref="LockRecursionException">
/// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high
/// enough that it would typically not be reached when the lock is used properly.
/// </exception>
public bool TryEnter(TimeSpan timeout) => TryEnter_Outlined(WaitHandle.ToTimeoutMilliseconds(timeout));
[MethodImpl(MethodImplOptions.NoInlining)]
private bool TryEnter_Outlined(int timeoutMs) => TryEnter_Inlined(timeoutMs).IsInitialized;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ThreadId TryEnter_Inlined(int timeoutMs)
{
Debug.Assert(timeoutMs >= -1);
ThreadId currentThreadId = ThreadId.Current_NoInitialize;
if (currentThreadId.IsInitialized && State.TryLock(this))
{
Debug.Assert(!new ThreadId(_owningThreadId).IsInitialized);
Debug.Assert(_recursionCount == 0);
_owningThreadId = currentThreadId.Id;
return currentThreadId;
}
return TryEnterSlow(timeoutMs, currentThreadId);
}
/// <summary>
/// Exits the lock.
/// </summary>
/// <remarks>
/// If the calling thread holds the lock multiple times, such as recursively, the lock is exited only once. The
/// calling thread should ensure that each enter is matched with an exit.
/// </remarks>
/// <exception cref="SynchronizationLockException">
/// The calling thread does not hold the lock.
/// </exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Exit()
{
var owningThreadId = new ThreadId(_owningThreadId);
if (!owningThreadId.IsInitialized || owningThreadId.Id != ThreadId.Current_NoInitialize.Id)
{
ThrowHelper.ThrowSynchronizationLockException_LockExit();
}
ExitImpl();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Exit(ThreadId currentThreadId)
{
Debug.Assert(currentThreadId.IsInitialized);
Debug.Assert(currentThreadId.Id == ThreadId.Current_NoInitialize.Id);
if (_owningThreadId != currentThreadId.Id)
{
ThrowHelper.ThrowSynchronizationLockException_LockExit();
}
ExitImpl();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ExitImpl()
{
Debug.Assert(new ThreadId(_owningThreadId).IsInitialized);
Debug.Assert(_owningThreadId == ThreadId.Current_NoInitialize.Id);
Debug.Assert(new State(this).IsLocked);
if (_recursionCount == 0)
{
_owningThreadId = 0;
State state = State.Unlock(this);
if (state.HasAnyWaiters)
{
SignalWaiterIfNecessary(state);
}
}
else
{
_recursionCount--;
}
}
private static bool IsAdaptiveSpinEnabled(short minSpinCountForAdaptiveSpin) => minSpinCountForAdaptiveSpin <= 0;
[MethodImpl(MethodImplOptions.NoInlining)]
private ThreadId TryEnterSlow(int timeoutMs, ThreadId currentThreadId)
{
Debug.Assert(timeoutMs >= -1);
if (!currentThreadId.IsInitialized)
{
// The thread info hasn't been initialized yet for this thread, and the fast path hasn't been tried yet. After
// initializing the thread info, try the fast path first.
currentThreadId.InitializeForCurrentThread();
Debug.Assert(_owningThreadId != currentThreadId.Id);
if (State.TryLock(this))
{
goto Locked;
}
}
else if (_owningThreadId == currentThreadId.Id)
{
Debug.Assert(new State(this).IsLocked);
uint newRecursionCount = _recursionCount + 1;
if (newRecursionCount != 0)
{
_recursionCount = newRecursionCount;
return currentThreadId;
}
throw new LockRecursionException(SR.Lock_Enter_LockRecursionException);
}
if (timeoutMs == 0)
{
return new ThreadId(0);
}
//
// At this point, a full lock attempt has been made, and it's time to retry or wait for the lock.
//
// Notify the debugger that this thread is about to wait for a lock that is likely held by another thread. The
// debugger may choose to enable other threads to run to help resolve the dependency, or it may choose to abort the
// FuncEval here. The lock state is consistent here for an abort, whereas letting a FuncEval continue to run could
// lead to the FuncEval timing out and potentially aborting at an arbitrary place where the lock state may not be
// consistent.
Debugger.NotifyOfCrossThreadDependency();
if (LazyInitializeOrEnter() == TryLockResult.Locked)
{
goto Locked;
}
short maxSpinCount = s_maxSpinCount;
if (maxSpinCount == 0)
{
goto Wait;
}
short minSpinCountForAdaptiveSpin = s_minSpinCountForAdaptiveSpin;
short spinCount = _spinCount;
if (spinCount < 0)
{
// When negative, the spin count serves as a counter for contentions such that a spin-wait can be attempted
// periodically to see if it would be beneficial. Increment the spin count and skip spin-waiting.
Debug.Assert(IsAdaptiveSpinEnabled(minSpinCountForAdaptiveSpin));
_spinCount = (short)(spinCount + 1);
goto Wait;
}
// Try to acquire the lock, and check if non-waiters should stop preempting waiters. If this thread should not
// preempt waiters, skip spin-waiting. Upon contention, register a spinner.
TryLockResult tryLockResult = State.TryLockBeforeSpinLoop(this, spinCount, out bool isFirstSpinner);
if (tryLockResult != TryLockResult.Spin)
{
goto LockedOrWait;
}
// Lock was not acquired and a spinner was registered
if (isFirstSpinner)
{
// Whether a full-length spin-wait would be effective is determined by having the first spinner do a full-length
// spin-wait to see if it is effective. Shorter spin-waits would more often be ineffective just because they are
// shorter.
spinCount = maxSpinCount;
}
for (short spinIndex = 0; ;)
{
LowLevelSpinWaiter.Wait(spinIndex, SpinSleep0Threshold, isSingleProcessor: false);
if (++spinIndex >= spinCount)
{
// The last lock attempt for this spin will be done after the loop
break;
}
// Try to acquire the lock and unregister the spinner
tryLockResult = State.TryLockInsideSpinLoop(this);
if (tryLockResult == TryLockResult.Spin)
{
continue;
}
if (tryLockResult == TryLockResult.Locked)
{
if (isFirstSpinner && IsAdaptiveSpinEnabled(minSpinCountForAdaptiveSpin))
{
// Since the first spinner does a full-length spin-wait, and to keep upward and downward changes to the
// spin count more balanced, only the first spinner adjusts the spin count
spinCount = _spinCount;
if (spinCount < maxSpinCount)
{
_spinCount = (short)(spinCount + 1);
}
}
goto Locked;
}
// The lock was not acquired and the spinner was not unregistered, stop spinning
Debug.Assert(tryLockResult == TryLockResult.Wait);
break;
}
// Unregister the spinner and try to acquire the lock
tryLockResult = State.TryLockAfterSpinLoop(this);
if (isFirstSpinner && IsAdaptiveSpinEnabled(minSpinCountForAdaptiveSpin))
{
// Since the first spinner does a full-length spin-wait, and to keep upward and downward changes to the
// spin count more balanced, only the first spinner adjusts the spin count
if (tryLockResult == TryLockResult.Locked)
{
spinCount = _spinCount;
if (spinCount < maxSpinCount)
{
_spinCount = (short)(spinCount + 1);
}
}
else
{
// If the spin count is already zero, skip spin-waiting for a while, even for the first spinners. After a
// number of contentions, the first spinner will attempt a spin-wait again to see if it is effective.
Debug.Assert(tryLockResult == TryLockResult.Wait);
spinCount = _spinCount;
_spinCount = spinCount > 0 ? (short)(spinCount - 1) : minSpinCountForAdaptiveSpin;
}
}
LockedOrWait:
Debug.Assert(tryLockResult != TryLockResult.Spin);
if (tryLockResult == TryLockResult.Wait)
{
goto Wait;
}
Debug.Assert(tryLockResult == TryLockResult.Locked);
Locked:
Debug.Assert(!new ThreadId(_owningThreadId).IsInitialized);
Debug.Assert(_recursionCount == 0);
_owningThreadId = currentThreadId.Id;
return currentThreadId;
Wait:
bool areContentionEventsEnabled =
NativeRuntimeEventSource.Log.IsEnabled(
EventLevel.Informational,
NativeRuntimeEventSource.Keywords.ContentionKeyword);
AutoResetEvent waitEvent = _waitEvent ?? CreateWaitEvent(areContentionEventsEnabled);
if (State.TryLockBeforeWait(this))
{
// Lock was acquired and a waiter was not registered
goto Locked;
}
// Lock was not acquired and a waiter was registered. All following paths need to unregister the waiter, including
// exceptional paths.
try
{
Interlocked.Increment(ref s_contentionCount);
long waitStartTimeTicks = 0;
if (areContentionEventsEnabled)
{
NativeRuntimeEventSource.Log.ContentionStart(this);
waitStartTimeTicks = Stopwatch.GetTimestamp();
}
using ThreadBlockingInfo.Scope threadBlockingScope = new(this, timeoutMs);
bool acquiredLock = false;
int waitStartTimeMs = timeoutMs < 0 ? 0 : Environment.TickCount;
int remainingTimeoutMs = timeoutMs;
while (true)
{
if (!waitEvent.WaitOneNoCheck(remainingTimeoutMs, new State(this).UseTrivialWaits))
{
break;
}
// Spin a bit while trying to acquire the lock. This has a few benefits:
// - Spinning helps to reduce waiter starvation. Since other non-waiter threads can take the lock while
// there are waiters (see State.TryLock()), once a waiter wakes it will be able to better compete with
// other spinners for the lock.
// - If there is another thread that is repeatedly acquiring and releasing the lock, spinning before waiting
// again helps to prevent a waiter from repeatedly context-switching in and out
// - Further in the same situation above, waking up and waiting shortly thereafter deprioritizes this waiter
// because events release waiters in FIFO order. Spinning a bit helps a waiter to retain its priority at
// least for one spin duration before it gets deprioritized behind all other waiters.
for (short spinIndex = 0; spinIndex < maxSpinCount; spinIndex++)
{
if (State.TryLockInsideWaiterSpinLoop(this))
{
acquiredLock = true;
break;
}
LowLevelSpinWaiter.Wait(spinIndex, SpinSleep0Threshold, isSingleProcessor: false);
}
if (acquiredLock)
{
break;
}
if (State.TryLockAfterWaiterSpinLoop(this))
{
acquiredLock = true;
break;
}
if (remainingTimeoutMs < 0)
{
continue;
}
uint waitDurationMs = (uint)(Environment.TickCount - waitStartTimeMs);
if (waitDurationMs >= (uint)timeoutMs)
{
break;
}
remainingTimeoutMs = timeoutMs - (int)waitDurationMs;
}
if (acquiredLock)
{
// In NativeAOT, ensure that class construction cycles do not occur after the lock is acquired but before
// the state is fully updated. Update the state to fully reflect that this thread owns the lock before doing
// other things.
Debug.Assert(!new ThreadId(_owningThreadId).IsInitialized);
Debug.Assert(_recursionCount == 0);
_owningThreadId = currentThreadId.Id;
if (areContentionEventsEnabled)
{
double waitDurationNs =
(Stopwatch.GetTimestamp() - waitStartTimeTicks) * 1_000_000_000.0 / Stopwatch.Frequency;
NativeRuntimeEventSource.Log.ContentionStop(waitDurationNs);
}
return currentThreadId;
}
}
catch // run this code before exception filters in callers
{
State.UnregisterWaiter(this);
throw;
}
State.UnregisterWaiter(this);
return new ThreadId(0);
}
private void ResetWaiterStartTime() => _waiterStartTimeMs = 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RecordWaiterStartTime()
{
ushort currentTimeMs = (ushort)Environment.TickCount;
if (currentTimeMs == 0)
{
// Don't record zero, that value is reserved for indicating that a time is not recorded
currentTimeMs--;
}
_waiterStartTimeMs = currentTimeMs;
}
private bool ShouldStopPreemptingWaiters
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// If the recorded time is zero, a time has not been recorded yet
ushort waiterStartTimeMs = _waiterStartTimeMs;
return
waiterStartTimeMs != 0 &&
(ushort)(Environment.TickCount - waiterStartTimeMs) >= MaxDurationMsForPreemptingWaiters;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private AutoResetEvent CreateWaitEvent(bool areContentionEventsEnabled)
{
var newWaitEvent = new AutoResetEvent(false);
AutoResetEvent? waitEventBeforeUpdate = Interlocked.CompareExchange(ref _waitEvent, newWaitEvent, null);
if (waitEventBeforeUpdate == null)
{
// Also check NativeRuntimeEventSource.Log.IsEnabled() to enable trimming
if (areContentionEventsEnabled && NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ContentionLockCreated(this);
}
return newWaitEvent;
}
newWaitEvent.Dispose();
return waitEventBeforeUpdate;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void SignalWaiterIfNecessary(State state)
{
if (State.TrySetIsWaiterSignaledToWake(this, state))
{
// Signal a waiter to wake
Debug.Assert(_waitEvent != null);
bool signaled = _waitEvent.Set();
Debug.Assert(signaled);
}
}
/// <summary>
/// <code>true</code> if the lock is held by the calling thread, <code>false</code> otherwise.
/// </summary>
public bool IsHeldByCurrentThread
{
get
{
var owningThreadId = new ThreadId(_owningThreadId);
bool isHeld = owningThreadId.IsInitialized && owningThreadId.Id == ThreadId.Current_NoInitialize.Id;
Debug.Assert(!isHeld || new State(this).IsLocked);
return isHeld;
}
}
internal static long ContentionCount => s_contentionCount;
internal void Dispose() => _waitEvent?.Dispose();
internal nint LockIdForEvents
{
get
{
Debug.Assert(_waitEvent != null);
return _waitEvent.SafeWaitHandle.DangerousGetHandle();
}
}
internal ulong OwningThreadId => _owningThreadId;
private static short DetermineMaxSpinCount()
{
if (IsSingleProcessor)
{
return 0;
}
return
AppContextConfigHelper.GetInt16Config(
"System.Threading.Lock.SpinCount",
"DOTNET_Lock_SpinCount",
DefaultMaxSpinCount,
allowNegative: false);
}
// When the returned value is zero or negative, indicates the lowest value that the _spinCount field will have when
// adaptive spin chooses to pause spin-waiting, see the comment on the _spinCount field for more information. When the
// returned value is positive, adaptive spin is disabled.
private static short DetermineMinSpinCountForAdaptiveSpin()
{
// The config var can be set to -1 to disable adaptive spin
short adaptiveSpinPeriod =
AppContextConfigHelper.GetInt16Config(
"System.Threading.Lock.AdaptiveSpinPeriod",
"DOTNET_Lock_AdaptiveSpinPeriod",
DefaultAdaptiveSpinPeriod,
allowNegative: true);
if (adaptiveSpinPeriod < -1)
{
adaptiveSpinPeriod = DefaultAdaptiveSpinPeriod;
}
return (short)-adaptiveSpinPeriod;
}
private struct State : IEquatable<State>
{
// Layout constants for Lock._state
private const uint IsLockedMask = (uint)1 << 0; // bit 0
private const uint ShouldNotPreemptWaitersMask = (uint)1 << 1; // bit 1
private const uint SpinnerCountIncrement = (uint)1 << 2; // bits 2-4
private const uint SpinnerCountMask = (uint)0x7 << 2;
private const uint IsWaiterSignaledToWakeMask = (uint)1 << 5; // bit 5
private const uint UseTrivialWaitsMask = (uint)1 << 6; // bit 6
private const uint WaiterCountIncrement = (uint)1 << 7; // bits 7-31
private uint _state;
public State(Lock lockObj) : this(lockObj._state) { }
private State(uint state) => _state = state;
public static uint InitialStateValue => 0;
public static uint LockedStateValue => IsLockedMask;
private static uint Neg(uint state) => (uint)-(int)state;
public bool IsInitialState => this == default;
public bool IsLocked => (_state & IsLockedMask) != 0;
private void SetIsLocked()
{
Debug.Assert(!IsLocked);
_state += IsLockedMask;
}
private bool ShouldNotPreemptWaiters => (_state & ShouldNotPreemptWaitersMask) != 0;
private void SetShouldNotPreemptWaiters()
{
Debug.Assert(!ShouldNotPreemptWaiters);
Debug.Assert(HasAnyWaiters);
_state += ShouldNotPreemptWaitersMask;
}
private void ClearShouldNotPreemptWaiters()
{
Debug.Assert(ShouldNotPreemptWaiters);
_state -= ShouldNotPreemptWaitersMask;
}
private bool ShouldNonWaiterAttemptToAcquireLock
{
get
{
Debug.Assert(HasAnyWaiters || !ShouldNotPreemptWaiters);
return (_state & (IsLockedMask | ShouldNotPreemptWaitersMask)) == 0;
}
}
private bool HasAnySpinners => (_state & SpinnerCountMask) != 0;
private bool TryIncrementSpinnerCount()
{
uint newState = _state + SpinnerCountIncrement;
if (new State(newState).HasAnySpinners) // overflow check
{
_state = newState;
return true;
}
return false;
}
private void DecrementSpinnerCount()
{
Debug.Assert(HasAnySpinners);
_state -= SpinnerCountIncrement;
}
private bool IsWaiterSignaledToWake => (_state & IsWaiterSignaledToWakeMask) != 0;
private void SetIsWaiterSignaledToWake()
{
Debug.Assert(HasAnyWaiters);
Debug.Assert(NeedToSignalWaiter);
_state += IsWaiterSignaledToWakeMask;
}
private void ClearIsWaiterSignaledToWake()
{
Debug.Assert(IsWaiterSignaledToWake);
_state -= IsWaiterSignaledToWakeMask;
}
// Trivial waits are:
// - Not interruptible by Thread.Interrupt
// - Don't allow reentrance through APCs or message pumping
// - Not forwarded to SynchronizationContext wait overrides
public bool UseTrivialWaits => (_state & UseTrivialWaitsMask) != 0;
public static void InitializeUseTrivialWaits(Lock lockObj, bool useTrivialWaits)
{
Debug.Assert(lockObj._state == 0);
if (useTrivialWaits)
{
lockObj._state = UseTrivialWaitsMask;
}
}
public bool HasAnyWaiters => _state >= WaiterCountIncrement;
private bool TryIncrementWaiterCount()
{
uint newState = _state + WaiterCountIncrement;
if (new State(newState).HasAnyWaiters) // overflow check
{
_state = newState;
return true;
}
return false;
}
private void DecrementWaiterCount()
{
Debug.Assert(HasAnyWaiters);
_state -= WaiterCountIncrement;
}
public bool NeedToSignalWaiter
{
get
{
Debug.Assert(HasAnyWaiters);
return (_state & (SpinnerCountMask | IsWaiterSignaledToWakeMask)) == 0;
}
}
public static bool operator ==(State state1, State state2) => state1._state == state2._state;
public static bool operator !=(State state1, State state2) => !(state1 == state2);
bool IEquatable<State>.Equals(State other) => this == other;
public override bool Equals(object? obj) => obj is State other && this == other;
public override int GetHashCode() => (int)_state;
private static State CompareExchange(Lock lockObj, State toState, State fromState) =>
new State(Interlocked.CompareExchange(ref lockObj._state, toState._state, fromState._state));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryLock(Lock lockObj)
{
// The lock is mostly fair to release waiters in a typically FIFO order (though the order is not guaranteed).
// However, it allows non-waiters to acquire the lock if it's available to avoid lock convoys.
//
// Lock convoys can be detrimental to performance in scenarios where work is being done on multiple threads and
// the work involves periodically taking a particular lock for a short time to access shared resources. With a
// lock convoy, once there is a waiter for the lock (which is not uncommon in such scenarios), a worker thread
// would be forced to context-switch on the subsequent attempt to acquire the lock, often long before the worker
// thread exhausts its time slice. This process repeats as long as the lock has a waiter, forcing every worker
// to context-switch on each attempt to acquire the lock, killing performance and creating a positive feedback
// loop that makes it more likely for the lock to have waiters. To avoid the lock convoy, each worker needs to
// be allowed to acquire the lock multiple times in sequence despite there being a waiter for the lock in order
// to have the worker continue working efficiently during its time slice as long as the lock is not contended.
//
// This scheme has the possibility to starve waiters. Waiter starvation is mitigated by other means, see
// TryLockBeforeSpinLoop() and references to ShouldNotPreemptWaiters.
var state = new State(lockObj);
if (!state.ShouldNonWaiterAttemptToAcquireLock)
{
return false;
}
State newState = state;
newState.SetIsLocked();
return CompareExchange(lockObj, newState, state) == state;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static State Unlock(Lock lockObj)
{
Debug.Assert(IsLockedMask == 1);
var state = new State(Interlocked.Decrement(ref lockObj._state));
Debug.Assert(!state.IsLocked);
return state;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TryLockResult TryLockBeforeSpinLoop(Lock lockObj, short spinCount, out bool isFirstSpinner)
{
// Normally, threads are allowed to preempt waiters to acquire the lock in order to avoid creating lock convoys,
// see TryLock(). There can be cases where waiters can be easily starved as a result. For example, a thread that
// holds a lock for a significant amount of time (much longer than the time it takes to do a context switch),
// then releases and reacquires the lock in quick succession, and repeats. Though a waiter would be woken upon
// lock release, usually it will not have enough time to context-switch-in and take the lock, and can be starved
// for an unreasonably long duration.
//
// In order to prevent such starvation and force a bit of fair forward progress, it is sometimes necessary to
// change the normal policy and disallow threads from preempting waiters. ShouldNotPreemptWaiters() indicates
// the current state of the policy and this method determines whether the policy should be changed to disallow
// non-waiters from preempting waiters.
// - When the first waiter begins waiting, it records the current time as a "waiter starvation start time".
// That is a point in time after which no forward progress has occurred for waiters. When a waiter acquires
// the lock, the time is updated to the current time.
// - This method checks whether the starvation duration has crossed a threshold and if so, sets
// ShouldNotPreemptWaitersMask
//
// When unreasonable starvation is occurring, the lock will be released occasionally and if caused by spinners,
// those threads may start to spin again.
// - Before starting to spin this method is called. If ShouldNotPreemptWaitersMask is set, the spinner will
// skip spinning and wait instead. Spinners that are already registered at the time
// ShouldNotPreemptWaitersMask is set will stop spinning as necessary. Eventually, all spinners will drain
// and no new ones will be registered.
// - Upon releasing a lock, if there are no spinners, a waiter will be signaled to wake. On that path,
// TrySetIsWaiterSignaledToWake() is called.
// - Eventually, after spinners have drained, only a waiter will be able to acquire the lock. When a waiter
// acquires the lock, or when the last waiter unregisters itself, ShouldNotPreemptWaitersMask is cleared to
// restore the normal policy.
Debug.Assert(spinCount >= 0);
isFirstSpinner = false;
var state = new State(lockObj);
while (true)
{
State newState = state;
TryLockResult result = TryLockResult.Spin;
if (newState.HasAnyWaiters)
{
if (newState.ShouldNotPreemptWaiters)
{
return TryLockResult.Wait;
}
if (lockObj.ShouldStopPreemptingWaiters)
{
newState.SetShouldNotPreemptWaiters();
result = TryLockResult.Wait;
}
}
if (result == TryLockResult.Spin)
{
Debug.Assert(!newState.ShouldNotPreemptWaiters);
if (!newState.IsLocked)
{
newState.SetIsLocked();
result = TryLockResult.Locked;
}
else if ((newState.HasAnySpinners && spinCount == 0) || !newState.TryIncrementSpinnerCount())
{
return TryLockResult.Wait;
}
}
State stateBeforeUpdate = CompareExchange(lockObj, newState, state);
if (stateBeforeUpdate == state)
{
if (result == TryLockResult.Spin && !state.HasAnySpinners)
{
isFirstSpinner = true;
}
return result;
}
state = stateBeforeUpdate;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TryLockResult TryLockInsideSpinLoop(Lock lockObj)
{
// This method is called from inside a spin loop, it must unregister the spinner if the lock is acquired
var state = new State(lockObj);
while (true)
{
Debug.Assert(state.HasAnySpinners);
if (!state.ShouldNonWaiterAttemptToAcquireLock)
{
return state.ShouldNotPreemptWaiters ? TryLockResult.Wait : TryLockResult.Spin;
}
State newState = state;
newState.SetIsLocked();
newState.DecrementSpinnerCount();
State stateBeforeUpdate = CompareExchange(lockObj, newState, state);
if (stateBeforeUpdate == state)
{
return TryLockResult.Locked;
}
state = stateBeforeUpdate;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TryLockResult TryLockAfterSpinLoop(Lock lockObj)
{
// This method is called at the end of a spin loop, it must unregister the spinner always and acquire the lock
// if it's available. If the lock is available, a spinner must acquire the lock along with unregistering itself,