Skip to content

Commit

Permalink
Check for time-sensitive work when worker thread starvation is ongoing (
Browse files Browse the repository at this point in the history
#61931)

- Otherwise timer callbacks may not run when worker threads are continually starved
- The change is similar to what was done in CoreCLR's native thread pool
- Fixes #61804
  • Loading branch information
kouvel authored Dec 15, 2021
1 parent fb56c4c commit de9467c
Showing 1 changed file with 16 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ public int Count
}

internal bool loggingEnabled;
private bool _dispatchTimeSensitiveWorkFirst;
internal readonly ConcurrentQueue<object> workItems = new ConcurrentQueue<object>(); // SOS's ThreadPool command depends on this name
internal readonly ConcurrentQueue<IThreadPoolWorkItem>? timeSensitiveWorkQueue =
ThreadPool.SupportsTimeSensitiveWorkItems ? new ConcurrentQueue<IThreadPoolWorkItem>() : null;
Expand Down Expand Up @@ -650,6 +651,21 @@ internal static bool Dispatch()
int startTickCount = Environment.TickCount;

object? workItem = null;
#pragma warning disable CS0162 // Unreachable code detected. SupportsTimeSensitiveWorkItems may be a constant in some runtimes.
if (ThreadPool.SupportsTimeSensitiveWorkItems)
{
// Alternate between checking for time-sensitive work or other work first, that way both sets of work items
// get a chance to run in situations where worker threads are starved and work items that run also take over
// the thread, sustaining starvation. For example, if time-sensitive work is always checked last here, timer
// callbacks may not run when worker threads are continually starved.
bool dispatchTimeSensitiveWorkFirst = workQueue._dispatchTimeSensitiveWorkFirst;
workQueue._dispatchTimeSensitiveWorkFirst = !dispatchTimeSensitiveWorkFirst;
if (dispatchTimeSensitiveWorkFirst)
{
workItem = workQueue.TryDequeueTimeSensitiveWorkItem();
}
}
#pragma warning restore CS0162

//
// Loop until our quantum expires or there is no work.
Expand Down

0 comments on commit de9467c

Please sign in to comment.