Skip to content

Commit

Permalink
[NativeAOT] Fix assert in Thread.SpinWait(0) (dotnet#73033)
Browse files Browse the repository at this point in the history
* do not inline long wait
  • Loading branch information
VSadov authored Jul 29, 2022
1 parent 9b63001 commit 5331568
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/coreclr/nativeaot/Runtime/MiscHelpers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ COOP_PINVOKE_HELPER(void, RhDebugBreak, ())
// Busy spin for the given number of iterations.
EXTERN_C NATIVEAOT_API void __cdecl RhSpinWait(int32_t iterations)
{
ASSERT(iterations > 0);

// limit the spin count in coop mode.
ASSERT_MSG(iterations <= 10000 || !ThreadStore::GetCurrentThread()->IsCurrentThreadInCooperativeMode(),
"This is too long wait for coop mode. You must p/invoke with GC transition.");

YieldProcessorNormalizationInfo normalizationInfo;
YieldProcessorNormalizedForPreSkylakeCount(normalizationInfo, iterations);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,11 @@ internal static unsafe void RhUnbox(object? obj, ref byte data, EETypePtr pUnbox
[UnmanagedCallConv(CallConvs = new Type[] { typeof(CallConvCdecl) })]
internal static partial void RhSpinWait(int iterations);

// Call RhSpinWait with a GC transition
[LibraryImport(RuntimeLibrary, EntryPoint = "RhSpinWait")]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(CallConvCdecl) })]
internal static partial void RhLongSpinWait(int iterations);

// Yield the cpu to another thread ready to process, if one is available.
[LibraryImport(RuntimeLibrary, EntryPoint = "RhYield")]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(CallConvCdecl) })]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,30 @@ public bool Join(int millisecondsTimeout)
/// </summary>
internal const int OptimalMaxSpinWaitsPerSpinIteration = 64;

public static void SpinWait(int iterations) => RuntimeImports.RhSpinWait(iterations);
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LongSpinWait(int iterations)
{
RuntimeImports.RhLongSpinWait(iterations);
}

public static void SpinWait(int iterations)
{
if (iterations <= 0)
return;

// Max iterations to be done in RhSpinWait.
// RhSpinWait does not switch GC modes and we want to avoid native spinning in coop mode for too long.
const int spinWaitCoopThreshold = 10000;

if (iterations > spinWaitCoopThreshold)
{
LongSpinWait(iterations);
}
else
{
RuntimeImports.RhSpinWait(iterations);
}
}

[MethodImpl(MethodImplOptions.NoInlining)] // Slow path method. Make sure that the caller frame does not pay for PInvoke overhead.
public static bool Yield() => RuntimeImports.RhYield();
Expand Down

0 comments on commit 5331568

Please sign in to comment.