Skip to content

Commit 3f38971

Browse files
authored
Moved a static field initialization from Thread to ProcessorIdCache (dotnet#114227)
Presence of `.cctor` in `Thread` can cause circular dependency if Lock needs to block while Thread .cctor has not run yet. 1. Lock needs to wait on a WaitHandle 2. WaitHandle needs Thread.CurrentThread 3. if Thread's .cctor has not run yet, it needs to run. (it is unusual for this to be the first use of Thread, but the activation pattern in dotnet#113949 made it possible) 4. .cctor needs to take a Lock, so we go to `#1` Fixes: dotnet#113949
1 parent fc856a2 commit 3f38971

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

src/libraries/System.Private.CoreLib/src/System/Threading/ProcessorIdCache.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ internal static class ProcessorIdCache
2222
// We will not adjust higher than this though.
2323
private const int MaxIdRefreshRate = 5000;
2424

25+
// a speed check will determine refresh rate of the cache and will report if caching is not advisable.
26+
// we will record that in a readonly static so that it could become a JIT constant and bypass caching entirely.
27+
private static readonly bool s_isProcessorNumberReallyFast = ProcessorIdCache.ProcessorNumberSpeedCheck();
28+
2529
private static int RefreshCurrentProcessorId()
2630
{
2731
int currentProcessorId = Thread.GetCurrentProcessorNumber();
@@ -44,6 +48,9 @@ private static int RefreshCurrentProcessorId()
4448
[MethodImpl(MethodImplOptions.AggressiveInlining)]
4549
internal static int GetCurrentProcessorId()
4650
{
51+
if (s_isProcessorNumberReallyFast)
52+
return Thread.GetCurrentProcessorNumber();
53+
4754
int currentProcessorIdCache = t_currentProcessorIdCache--;
4855
if ((currentProcessorIdCache & ProcessorIdCacheCountDownMask) == 0)
4956
{

src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -719,16 +719,9 @@ public static void SetData(LocalDataStoreSlot slot, object? value)
719719
[MethodImpl(MethodImplOptions.AggressiveInlining)]
720720
public static int GetCurrentProcessorId()
721721
{
722-
if (s_isProcessorNumberReallyFast)
723-
return GetCurrentProcessorNumber();
724-
725722
return ProcessorIdCache.GetCurrentProcessorId();
726723
}
727724

728-
// a speed check will determine refresh rate of the cache and will report if caching is not advisable.
729-
// we will record that in a readonly static so that it could become a JIT constant and bypass caching entirely.
730-
private static readonly bool s_isProcessorNumberReallyFast = ProcessorIdCache.ProcessorNumberSpeedCheck();
731-
732725
#if FEATURE_WASM_MANAGED_THREADS
733726
[ThreadStatic]
734727
public static bool ThrowOnBlockingWaitOnJSInteropThread;

0 commit comments

Comments
 (0)