Skip to content
New issue

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

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

Already on GitHub? # to your account

[8.0] Make counting of IO completion work items more precise on Windows #112795

Open
wants to merge 4 commits into
base: release/8.0-staging
Choose a base branch
from
Open
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 @@ -15,6 +15,7 @@ internal sealed class ThreadInt64PersistentCounter
private static List<ThreadLocalNodeFinalizationHelper>? t_nodeFinalizationHelpers;

private long _overflowCount;
private long _lastReturnedCount;

// dummy node serving as a start and end of the ring list
private readonly ThreadLocalNode _nodes;
Expand All @@ -31,6 +32,13 @@ public static void Increment(object threadLocalCountObject)
Unsafe.As<ThreadLocalNode>(threadLocalCountObject).Increment();
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Decrement(object threadLocalCountObject)
{
Debug.Assert(threadLocalCountObject is ThreadLocalNode);
Unsafe.As<ThreadLocalNode>(threadLocalCountObject).Decrement();
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(object threadLocalCountObject, uint count)
{
Expand Down Expand Up @@ -76,6 +84,17 @@ public long Count
count += node.Count;
node = node._next;
}

// Ensure that the returned value is monotonically increasing
long lastReturnedCount = _lastReturnedCount;
if (count > lastReturnedCount)
{
_lastReturnedCount = count;
}
else
{
count = lastReturnedCount;
}
}
finally
{
Expand Down Expand Up @@ -134,6 +153,18 @@ public void Increment()
OnAddOverflow(1);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Decrement()
{
if (_count != 0)
{
_count--;
return;
}

OnAddOverflow(-1);
}

public void Add(uint count)
{
Debug.Assert(count != 0);
Expand All @@ -149,7 +180,7 @@ public void Add(uint count)
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void OnAddOverflow(uint count)
private void OnAddOverflow(long count)
{
Debug.Assert(count != 0);

Expand All @@ -161,7 +192,7 @@ private void OnAddOverflow(uint count)
counter._lock.Acquire();
try
{
counter._overflowCount += (long)_count + count;
counter._overflowCount += _count + count;
_count = 0;
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1204,6 +1204,9 @@ void IThreadPoolWorkItem.Execute()
Interlocked.MemoryBarrier();
if (!_workItems.TryDequeue(out T workItem))
{
// Discount a work item here to avoid counting this queue processing work item
ThreadInt64PersistentCounter.Decrement(
ThreadPoolWorkQueueThreadLocals.threadLocals!.threadLocalCompletionCountObject!);
return;
}

Expand Down Expand Up @@ -1247,7 +1250,11 @@ void IThreadPoolWorkItem.Execute()
currentThread.ResetThreadPoolThread();
}

ThreadInt64PersistentCounter.Add(tl.threadLocalCompletionCountObject!, completedCount);
// Discount a work item here to avoid counting this queue processing work item
if (completedCount > 1)
{
ThreadInt64PersistentCounter.Add(tl.threadLocalCompletionCountObject!, completedCount - 1);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TestRuntime>true</TestRuntime>
</PropertyGroup>
<ItemGroup>
Expand Down
36 changes: 36 additions & 0 deletions src/libraries/System.Threading.ThreadPool/tests/ThreadPoolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,42 @@ public static void PrioritizationExperimentConfigVarTest()
}).Dispose();
}


[ConditionalFact(nameof(IsThreadingAndRemoteExecutorSupported))]
[PlatformSpecific(TestPlatforms.Windows)]
public static unsafe void ThreadPoolCompletedWorkItemCountTest()
{
// Run in a separate process to test in a clean thread pool environment such that we don't count external work items
RemoteExecutor.Invoke(() =>
{
const int WorkItemCount = 4;

int completedWorkItemCount = 0;
using var allWorkItemsCompleted = new AutoResetEvent(false);

IOCompletionCallback callback =
(errorCode, numBytes, innerNativeOverlapped) =>
{
Overlapped.Free(innerNativeOverlapped);
if (Interlocked.Increment(ref completedWorkItemCount) == WorkItemCount)
{
allWorkItemsCompleted.Set();
}
};
for (int i = 0; i < WorkItemCount; i++)
{
ThreadPool.UnsafeQueueNativeOverlapped(new Overlapped().Pack(callback, null));
}

allWorkItemsCompleted.CheckedWait();

// Allow work items to be marked as completed during this time
ThreadTestHelpers.WaitForCondition(() => ThreadPool.CompletedWorkItemCount >= WorkItemCount);
Thread.Sleep(50);
Assert.Equal(WorkItemCount, ThreadPool.CompletedWorkItemCount);
}).Dispose();
}

public static bool IsThreadingAndRemoteExecutorSupported =>
PlatformDetection.IsThreadingSupported && RemoteExecutor.IsSupported;

Expand Down
Loading