Skip to content

[NativeAOT] Implement Thread.Interrupt on Windows using QueueUserAPC #118302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,12 @@
<Compile Include="$(CommonPath)\Interop\Windows\Kernel32\Interop.DynamicLoad.cs">
<Link>Interop\Windows\Kernel32\Interop.DynamicLoad.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Interop\Windows\Kernel32\Interop.QueueUserAPC.cs">
<Link>Interop\Windows\Kernel32\Interop.QueueUserAPC.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Interop\Windows\Kernel32\Interop.Threading.cs">
<Link>Interop\Windows\Kernel32\Interop.Threading.cs</Link>
</Compile>
<Compile Include="System\Threading\Thread.NativeAot.Windows.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)'=='true'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,15 @@ public sealed partial class Thread
[ThreadStatic]
private static ComState t_comState;

[ThreadStatic]
private static bool t_interruptRequested;

private SafeWaitHandle _osHandle;

private ApartmentState _initialApartmentState = ApartmentState.Unknown;

private volatile bool _pendingInterrupt;

partial void PlatformSpecificInitialize();

// Platform-specific initialization of foreign threads, i.e. threads not created by Thread.Start
Expand Down Expand Up @@ -162,7 +167,40 @@ private bool JoinInternal(int millisecondsTimeout)
}
else
{
result = WaitHandle.WaitOneCore(waitHandle.DangerousGetHandle(), millisecondsTimeout, useTrivialWaits: false);
Thread? currentThread = t_currentThread;

// Check for pending interrupt from before thread started
if (currentThread is not null && currentThread._pendingInterrupt)
{
currentThread._pendingInterrupt = false;
throw new ThreadInterruptedException();
}

if (currentThread is not null)
{
currentThread.SetWaitSleepJoinState();
}

try
{
// Use alertable wait so we can be interrupted by APC
result = (int)Interop.Kernel32.WaitForSingleObjectEx(waitHandle.DangerousGetHandle(),
(uint)millisecondsTimeout, Interop.BOOL.TRUE);

// Check if we were interrupted by an APC
if (result == Interop.Kernel32.WAIT_IO_COMPLETION)
{
CheckForInterrupt();
return false; // Interrupted, so join did not complete
}
}
finally
{
if (currentThread is not null)
{
currentThread.ClearWaitSleepJoinState();
}
}
}

return result == (int)Interop.Kernel32.WAIT_OBJECT_0;
Expand Down Expand Up @@ -226,6 +264,21 @@ private static uint ThreadEntryPoint(IntPtr parameter)
return 0;
}

private static void CheckPendingInterrupt()
{
Thread? currentThread = t_currentThread;
if (currentThread is not null && currentThread._pendingInterrupt)
{
currentThread._pendingInterrupt = false;
throw new ThreadInterruptedException();
}
}

private static void CheckForPendingInterrupt()
{
CheckPendingInterrupt();
}

public ApartmentState GetApartmentState()
{
if (this != CurrentThread)
Expand Down Expand Up @@ -386,7 +439,51 @@ internal static Thread EnsureThreadPoolThreadInitialized()
return InitializeExistingThreadPoolThread();
}

public void Interrupt() { throw new PlatformNotSupportedException(); }
[UnmanagedCallersOnly]
private static void InterruptApcCallback(nint parameter)
{
// This is the native APC callback that sets the interrupt flag
// It runs in native code to avoid managed reentrancy issues
t_interruptRequested = true;
}

private static void CheckForInterrupt()
{
if (t_interruptRequested)
{
t_interruptRequested = false;
throw new ThreadInterruptedException();
}
}

public void Interrupt()
{
using (_lock.EnterScope())
{
// If thread is dead, do nothing
if (GetThreadStateBit(ThreadState.Stopped))
return;

// If thread hasn't started yet, set pending interrupt flag
if (GetThreadStateBit(ThreadState.Unstarted))
{
_pendingInterrupt = true;
return;
}

// Queue APC to interrupt the thread
SafeWaitHandle osHandle = _osHandle;
if (osHandle is not null && !osHandle.IsInvalid && !osHandle.IsClosed)
{
nint callbackPtr;
unsafe
{
callbackPtr = (nint)(delegate* unmanaged<nint, void>)&InterruptApcCallback;
}
Interop.Kernel32.QueueUserAPC(callbackPtr, osHandle.DangerousGetHandle(), IntPtr.Zero);
}
}
}

internal static bool ReentrantWaitsEnabled =>
GetCurrentApartmentType() == ApartmentType.STA;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public sealed partial class Thread

private static int s_foregroundRunningCount;

// Platform-specific method to check for pending interrupts when thread starts
partial void CheckForPendingInterrupt();

private Thread()
{
_managedThreadId = System.Threading.ManagedThreadId.GetCurrentThreadId();
Expand Down Expand Up @@ -450,6 +453,9 @@ private static void StartThread(IntPtr parameter)
IncrementRunningForeground();
}

// Check for any pending interrupt that was queued before the thread started
thread.CheckForPendingInterrupt();

try
{
StartHelper? startHelper = thread._startHelper;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
internal static partial class Kernel32
{
internal delegate void PAPCFUNC(nint dwParam);

[LibraryImport(Libraries.Kernel32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool QueueUserAPC(nint pfnAPC, nint hThread, nint dwData);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
internal static partial class Kernel32
{
[LibraryImport(Libraries.Kernel32)]
internal static partial uint SleepEx(uint dwMilliseconds, BOOL bAlertable);
}
}
2 changes: 0 additions & 2 deletions src/libraries/System.Threading.Thread/tests/ThreadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,6 @@ public static void LocalDataSlotTest()

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/49521", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/69919", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
public static void InterruptTest()
{
// Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets
Expand Down Expand Up @@ -966,7 +965,6 @@ public static void InterruptTest()
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/69919", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/49521", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public static void InterruptInFinallyBlockTest_SkipOnDesktopFramework()
{
Expand Down
1 change: 0 additions & 1 deletion src/libraries/System.Threading/tests/MonitorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,6 @@ public static void ObjectHeaderSyncBlockTransitionTryEnterRaceTest()
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/49521", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/87718", TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
public static void InterruptWaitTest()
{
object obj = new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,12 +288,7 @@ public static int TestEntryPoint()
{
RunTestUsingInfiniteWait();
RunTestUsingTimedWait();

// Thread.Interrupt is not implemented on NativeAOT - https://github.com/dotnet/runtime/issues/69919
if (!TestLibrary.Utilities.IsNativeAot)
{
RunTestInterruptInfiniteWait();
}
RunTestInterruptInfiniteWait();

return result;
}
Expand Down
Loading