Repository navigation
Expand file tree
/
Copy pathThreadPoolWorkQueue.cs
More file actions
2015 lines (1739 loc) · 83.6 KB
/
Copy pathThreadPoolWorkQueue.cs
File metadata and controls
2015 lines (1739 loc) · 83.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
#if FEATURE_SINGLE_THREADED
using WorkQueue = System.Collections.Generic.Queue<object>;
#else
using WorkQueue = System.Collections.Concurrent.ConcurrentQueue<object>;
#endif
#if TARGET_WINDOWS
using IOCompletionPollerEvent = System.Threading.PortableThreadPool.IOCompletionPoller.Event;
#endif // TARGET_WINDOWS
namespace System.Threading
{
/// <summary>
/// Class for creating and managing a threadpool.
/// </summary>
internal sealed partial class ThreadPoolWorkQueue
{
internal static class WorkStealingQueueList
{
#pragma warning disable CA1825, IDE0300 // avoid the extra generic instantiation for Array.Empty<T>(); this is the only place we'll ever create this array
private static WorkStealingQueue[] s_queues = new WorkStealingQueue[0];
#pragma warning restore CA1825, IDE0300
public static WorkStealingQueue[] Queues => s_queues;
public static void Add(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = s_queues;
Debug.Assert(Array.IndexOf(oldQueues, queue) < 0);
var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
Array.Copy(oldQueues, newQueues, oldQueues.Length);
newQueues[^1] = queue;
if (Interlocked.CompareExchange(ref s_queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
public static void Remove(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = s_queues;
if (oldQueues.Length == 0)
{
return;
}
int pos = Array.IndexOf(oldQueues, queue);
if (pos < 0)
{
Debug.Fail("Should have found the queue");
return;
}
var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
if (pos == 0)
{
Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
}
else if (pos == oldQueues.Length - 1)
{
Array.Copy(oldQueues, newQueues, newQueues.Length);
}
else
{
Array.Copy(oldQueues, newQueues, pos);
Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
}
if (Interlocked.CompareExchange(ref s_queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
}
internal sealed class WorkStealingQueue
{
private const int INITIAL_SIZE = 32;
internal volatile object?[] m_array = new object[INITIAL_SIZE]; // SOS's ThreadPool command depends on this name
private volatile int m_mask = INITIAL_SIZE - 1;
#if DEBUG
// in debug builds, start at the end so we exercise the index reset logic.
private const int START_INDEX = int.MaxValue;
#else
private const int START_INDEX = 0;
#endif
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
public void LocalPush(object obj)
{
int tail = m_tailIndex;
// We're going to increment the tail; if we'll overflow, then we need to reset our counts
if (tail == int.MaxValue)
{
tail = LocalPush_HandleTailOverflow();
}
// When there are at least 2 elements' worth of space, we can take the fast path.
if (tail < m_headIndex + m_mask)
{
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
else
{
// We need to contend with foreign pops, so we lock.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
int head = m_headIndex;
int count = m_tailIndex - m_headIndex;
// If there is still space (one left), just add the element.
if (count >= m_mask)
{
// We're full; expand the queue by doubling its size.
var newArray = new object?[m_array.Length << 1];
for (int i = 0; i < m_array.Length; i++)
newArray[i] = m_array[(i + head) & m_mask];
// Reset the field values, incl. the mask.
m_array = newArray;
m_headIndex = 0;
m_tailIndex = tail = count;
m_mask = (m_mask << 1) | 1;
}
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int LocalPush_HandleTailOverflow()
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
int tail = m_tailIndex;
if (tail == int.MaxValue)
{
//
// Rather than resetting to zero, we'll just mask off the bits we don't care about.
// This way we don't need to rearrange the items already in the queue; they'll be found
// correctly exactly where they are. One subtlety here is that we need to make sure that
// if head is currently < tail, it remains that way. This happens to just fall out from
// the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
// bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
// for the head to end up > than the tail, since you can't set any more bits than all of
// them.
//
m_headIndex &= m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
Debug.Assert(m_headIndex <= m_tailIndex);
}
return tail;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: true);
}
}
public bool LocalFindAndPop(object obj)
{
// Fast path: check the tail. If equal, we can skip the lock.
if (m_array[(m_tailIndex - 1) & m_mask] == obj)
{
object? unused = LocalPop();
Debug.Assert(unused == null || unused == obj);
return unused != null;
}
// Else, do an O(N) search for the work item. The theory of work stealing and our
// inlining logic is that most waits will happen on recently queued work. And
// since recently queued work will be close to the tail end (which is where we
// begin our search), we will likely find it quickly. In the worst case, we
// will traverse the whole local queue; this is typically not going to be a
// problem (although degenerate cases are clearly an issue) because local work
// queues tend to be somewhat shallow in length, and because if we fail to find
// the work item, we are about to block anyway (which is very expensive).
for (int i = m_tailIndex - 2; i >= m_headIndex; i--)
{
if (m_array[i & m_mask] == obj)
{
// If we found the element, block out steals to avoid interference.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
// If we encountered a race condition, bail.
if (m_array[i & m_mask] == null)
return false;
// Otherwise, null out the element.
Volatile.Write(ref m_array[i & m_mask], null);
// And then check to see if we can fix up the indexes (if we're at
// the edge). If we can't, we just leave nulls in the array and they'll
// get filtered out eventually (but may lead to superfluous resizing).
if (i == m_tailIndex)
m_tailIndex--;
else if (i == m_headIndex)
m_headIndex++;
return true;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
return false;
}
public object? LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
private object? LocalPopCore()
{
while (true)
{
int tail = m_tailIndex;
if (m_headIndex >= tail)
{
return null;
}
// Decrement the tail using a fence to ensure subsequent read doesn't come before.
tail--;
Interlocked.Exchange(ref m_tailIndex, tail);
// If there is no interaction with a take, we can head down the fast path.
if (m_headIndex <= tail)
{
int idx = tail & m_mask;
object? obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Interaction with takes: 0 or 1 elements left.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_headIndex <= tail)
{
// Element still available. Take it.
int idx = tail & m_mask;
object? obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// If we encountered a race condition and element was stolen, restore the tail.
m_tailIndex = tail + 1;
return null;
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
public bool CanSteal => m_headIndex < m_tailIndex;
public object? TrySteal(ref bool missedSteal)
{
while (true)
{
if (CanSteal)
{
bool taken = false;
try
{
m_foreignLock.TryEnter(ref taken);
if (taken)
{
// Increment head, and ensure read of tail doesn't move before it (fence).
int head = m_headIndex;
Interlocked.Exchange(ref m_headIndex, head + 1);
if (head < m_tailIndex)
{
int idx = head & m_mask;
object? obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Failed, restore head.
m_headIndex = head;
}
}
}
finally
{
if (taken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
}
return null;
}
}
public int Count
{
get
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
return Math.Max(0, m_tailIndex - m_headIndex);
}
finally
{
if (lockTaken)
{
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
}
#if CORECLR
// This config var can be used to enable an experimental mode that may reduce the effects of some priority inversion
// issues seen in cases involving a lot of sync-over-async. See EnqueueForPrioritizationExperiment() for more
// information. The mode is experimental and may change in the future.
internal static readonly bool s_prioritizationExperiment =
AppContextConfigHelper.GetBooleanConfig(
"System.Threading.ThreadPool.PrioritizationExperiment",
"DOTNET_ThreadPool_PrioritizationExperiment",
defaultValue: false);
#endif
private const int ProcessorsPerAssignableWorkItemQueue = 16;
private static readonly int s_assignableWorkItemQueueCount =
Environment.ProcessorCount <= 32 ? 0 :
(Environment.ProcessorCount + (ProcessorsPerAssignableWorkItemQueue - 1)) / ProcessorsPerAssignableWorkItemQueue;
private bool _loggingEnabled;
private bool _dispatchNormalPriorityWorkFirst;
private bool _mayHaveHighPriorityWorkItems;
// SOS's ThreadPool command depends on the following names
internal readonly WorkQueue workItems = new WorkQueue();
internal readonly WorkQueue highPriorityWorkItems = new WorkQueue();
#if CORECLR
internal readonly WorkQueue lowPriorityWorkItems =
s_prioritizationExperiment ? new WorkQueue() : null!;
#endif
// SOS's ThreadPool command depends on the following name. The global queue doesn't scale well beyond a point of
// concurrency. Some additional queues may be added and assigned to a limited number of worker threads if necessary to
// help with limiting the concurrency level.
internal readonly WorkQueue[] _assignableWorkItemQueues =
new WorkQueue[s_assignableWorkItemQueueCount];
private readonly LowLevelLock _queueAssignmentLock = new();
private readonly int[] _assignedWorkItemQueueThreadCounts =
s_assignableWorkItemQueueCount > 0 ? new int[s_assignableWorkItemQueueCount] : Array.Empty<int>();
private object? _nextWorkItemToProcess;
// The scheme works as follows:
// - From NotScheduled, the only transition is to Scheduled when new items are enqueued and a thread is requested to process them.
// - From Scheduled, the only transition is to Determining right before trying to dequeue an item.
// - From Determining, it can go to either NotScheduled when no items are present in the queue (the previous thread processed all of them)
// or Scheduled if the queue is still not empty (let the current thread handle parallelization as convinient).
//
// The goal is to avoid requesting more threads than necessary, while still ensuring that all items are processed.
// Another thread isn't requested hastily while the state is Determining,
// instead the parallelizer takes care of that. We also ensure that only one thread can be parallelizing at any time.
private enum QueueProcessingStage
{
NotScheduled,
Determining,
Scheduled
}
[StructLayout(LayoutKind.Sequential)]
private struct CacheLineSeparated
{
private readonly Internal.PaddingFor32 pad1;
public QueueProcessingStage queueProcessingStage;
private readonly Internal.PaddingFor32 pad2;
}
private CacheLineSeparated _separated;
public ThreadPoolWorkQueue()
{
for (int i = 0; i < s_assignableWorkItemQueueCount; i++)
{
_assignableWorkItemQueues[i] = new WorkQueue();
}
RefreshLoggingEnabled();
}
private void AssignWorkItemQueue(ThreadPoolWorkQueueThreadLocals tl)
{
Debug.Assert(s_assignableWorkItemQueueCount > 0);
_queueAssignmentLock.Acquire();
// Determine the first queue that has not yet been assigned to the limit of worker threads
int queueIndex = -1;
int minCount = int.MaxValue;
int minCountQueueIndex = 0;
for (int i = 0; i < s_assignableWorkItemQueueCount; i++)
{
int count = _assignedWorkItemQueueThreadCounts[i];
Debug.Assert(count >= 0);
if (count < ProcessorsPerAssignableWorkItemQueue)
{
queueIndex = i;
_assignedWorkItemQueueThreadCounts[queueIndex] = count + 1;
break;
}
if (count < minCount)
{
minCount = count;
minCountQueueIndex = i;
}
}
if (queueIndex < 0)
{
// All queues have been fully assigned. Choose the queue that has been assigned to the least number of worker
// threads.
queueIndex = minCountQueueIndex;
_assignedWorkItemQueueThreadCounts[queueIndex]++;
}
_queueAssignmentLock.Release();
tl.queueIndex = queueIndex;
tl.assignedGlobalWorkItemQueue = _assignableWorkItemQueues[queueIndex];
}
private void TryReassignWorkItemQueue(ThreadPoolWorkQueueThreadLocals tl)
{
Debug.Assert(s_assignableWorkItemQueueCount > 0);
int queueIndex = tl.queueIndex;
if (queueIndex == 0)
{
return;
}
if (!_queueAssignmentLock.TryAcquire())
{
return;
}
// If the currently assigned queue is assigned to other worker threads, try to reassign an earlier queue to this
// worker thread if the earlier queue is not assigned to the limit of worker threads
Debug.Assert(_assignedWorkItemQueueThreadCounts[queueIndex] >= 0);
if (_assignedWorkItemQueueThreadCounts[queueIndex] > 1)
{
for (int i = 0; i < queueIndex; i++)
{
if (_assignedWorkItemQueueThreadCounts[i] < ProcessorsPerAssignableWorkItemQueue)
{
_assignedWorkItemQueueThreadCounts[queueIndex]--;
queueIndex = i;
_assignedWorkItemQueueThreadCounts[queueIndex]++;
break;
}
}
}
_queueAssignmentLock.Release();
tl.queueIndex = queueIndex;
tl.assignedGlobalWorkItemQueue = _assignableWorkItemQueues[queueIndex];
}
private void UnassignWorkItemQueue(ThreadPoolWorkQueueThreadLocals tl)
{
Debug.Assert(s_assignableWorkItemQueueCount > 0);
int queueIndex = tl.queueIndex;
_queueAssignmentLock.Acquire();
int newCount = --_assignedWorkItemQueueThreadCounts[queueIndex];
_queueAssignmentLock.Release();
Debug.Assert(newCount >= 0);
if (newCount > 0)
{
return;
}
// This queue is not assigned to any other worker threads. Move its work items to the global queue to prevent them
// from being starved for a long duration.
bool movedWorkItem = false;
WorkQueue queue = tl.assignedGlobalWorkItemQueue;
while (_assignedWorkItemQueueThreadCounts[queueIndex] <= 0 && queue.TryDequeue(out object? workItem))
{
workItems.Enqueue(workItem);
movedWorkItem = true;
}
if (movedWorkItem)
{
EnsureThreadRequested();
}
}
public ThreadPoolWorkQueueThreadLocals GetOrCreateThreadLocals() =>
ThreadPoolWorkQueueThreadLocals.threadLocals ?? CreateThreadLocals();
[MethodImpl(MethodImplOptions.NoInlining)]
private ThreadPoolWorkQueueThreadLocals CreateThreadLocals()
{
Debug.Assert(ThreadPoolWorkQueueThreadLocals.threadLocals == null);
return ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RefreshLoggingEnabled()
{
if (!FrameworkEventSource.Log.IsEnabled())
{
if (_loggingEnabled)
{
_loggingEnabled = false;
}
return;
}
RefreshLoggingEnabledFull();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void RefreshLoggingEnabledFull()
{
_loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void EnsureThreadRequested()
{
// Only request a thread if the stage is NotScheduled.
// Otherwise let the current requested thread handle parallelization.
if (Interlocked.Exchange(
ref _separated.queueProcessingStage,
QueueProcessingStage.Scheduled) == QueueProcessingStage.NotScheduled)
{
ThreadPool.RequestWorkerThread();
}
}
public void Enqueue(object callback, bool forceGlobal)
{
Debug.Assert((callback is IThreadPoolWorkItem) ^ (callback is Task));
if (_loggingEnabled && FrameworkEventSource.Log.IsEnabled())
FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback);
#if CORECLR
if (s_prioritizationExperiment)
{
EnqueueForPrioritizationExperiment(callback, forceGlobal);
}
else
#endif
{
ThreadPoolWorkQueueThreadLocals? tl;
if (!forceGlobal && (tl = ThreadPoolWorkQueueThreadLocals.threadLocals) != null)
{
tl.workStealingQueue.LocalPush(callback);
}
else
{
WorkQueue queue =
s_assignableWorkItemQueueCount > 0 && (tl = ThreadPoolWorkQueueThreadLocals.threadLocals) != null
? tl.assignedGlobalWorkItemQueue
: workItems;
queue.Enqueue(callback);
}
}
EnsureThreadRequested();
}
#if CORECLR
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnqueueForPrioritizationExperiment(object callback, bool forceGlobal)
{
ThreadPoolWorkQueueThreadLocals? tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
if (!forceGlobal && tl != null)
{
tl.workStealingQueue.LocalPush(callback);
return;
}
WorkQueue queue;
// This is a rough and experimental attempt at identifying work items that should be lower priority than other
// global work items (even ones that haven't been queued yet), and to queue them to a low-priority global queue that
// is checked after all other global queues. In some cases, a work item may queue another work item that is part of
// the same set of work. For global work items, the second work item would typically get queued behind other global
// work items. In some cases involving a lot of sync-over-async, that can significantly delay worker threads from
// getting unblocked.
if (tl == null && callback is QueueUserWorkItemCallbackBase)
{
queue = lowPriorityWorkItems;
}
else if (s_assignableWorkItemQueueCount > 0 && tl != null)
{
queue = tl.assignedGlobalWorkItemQueue;
}
else
{
queue = workItems;
}
queue.Enqueue(callback);
}
#endif
public void EnqueueAtHighPriority(object workItem)
{
Debug.Assert((workItem is IThreadPoolWorkItem) ^ (workItem is Task));
if (_loggingEnabled && FrameworkEventSource.Log.IsEnabled())
FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(workItem);
highPriorityWorkItems.Enqueue(workItem);
// If the change below is seen by another thread, ensure that the enqueued work item will also be visible
Volatile.Write(ref _mayHaveHighPriorityWorkItems, true);
EnsureThreadRequested();
}
internal static void TransferAllLocalWorkItemsToHighPriorityGlobalQueue()
{
// If there's no local queue, there's nothing to transfer.
if (ThreadPoolWorkQueueThreadLocals.threadLocals is not ThreadPoolWorkQueueThreadLocals tl)
{
return;
}
// Pop each work item off the local queue and push it onto the global. This is a
// bounded loop as no other thread is allowed to push into this thread's queue.
ThreadPoolWorkQueue queue = ThreadPool.s_workQueue;
bool addedHighPriorityWorkItem = false;
bool ensureThreadRequest = false;
while (tl.workStealingQueue.LocalPop() is object workItem)
{
// If there's an unexpected exception here that happens to get handled, the lost work item, or missing thread
// request, etc., may lead to other issues. A fail-fast or try-finally here could reduce the effect of such
// uncommon issues to various degrees, but it's also uncommon to check for unexpected exceptions.
try
{
queue.highPriorityWorkItems.Enqueue(workItem);
addedHighPriorityWorkItem = true;
}
catch (OutOfMemoryException)
{
// This is not expected to throw under normal circumstances
tl.workStealingQueue.LocalPush(workItem);
// A work item had been removed temporarily and other threads may have missed stealing it, so ensure that
// there will be a thread request
ensureThreadRequest = true;
break;
}
}
if (addedHighPriorityWorkItem)
{
Volatile.Write(ref queue._mayHaveHighPriorityWorkItems, true);
ensureThreadRequest = true;
}
if (ensureThreadRequest)
{
queue.EnsureThreadRequested();
}
}
internal static bool LocalFindAndPop(object callback)
{
ThreadPoolWorkQueueThreadLocals? tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
}
public object? Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
// Check for local work items
object? workItem = tl.workStealingQueue.LocalPop();
if (workItem != null)
{
return workItem;
}
if (_nextWorkItemToProcess != null)
{
workItem = Interlocked.Exchange(ref _nextWorkItemToProcess, null);
if (workItem != null)
{
return workItem;
}
}
// Check for high-priority work items
if (tl.isProcessingHighPriorityWorkItems)
{
if (highPriorityWorkItems.TryDequeue(out workItem))
{
return workItem;
}
tl.isProcessingHighPriorityWorkItems = false;
}
else if (
_mayHaveHighPriorityWorkItems &&
Interlocked.CompareExchange(ref _mayHaveHighPriorityWorkItems, false, true) &&
TryStartProcessingHighPriorityWorkItemsAndDequeue(tl, out workItem))
{
return workItem;
}
// Check for work items from the assigned global queue
if (s_assignableWorkItemQueueCount > 0 && tl.assignedGlobalWorkItemQueue.TryDequeue(out workItem))
{
return workItem;
}
// Check for work items from the global queue
if (workItems.TryDequeue(out workItem))
{
return workItem;
}
// Check for work items in other assignable global queues
uint randomValue = tl.random.NextUInt32();
if (s_assignableWorkItemQueueCount > 0)
{
int queueIndex = tl.queueIndex;
int c = s_assignableWorkItemQueueCount;
int maxIndex = c - 1;
for (int i = (int)(randomValue % (uint)c); c > 0; i = i < maxIndex ? i + 1 : 0, c--)
{
if (i != queueIndex && _assignableWorkItemQueues[i].TryDequeue(out workItem))
{
return workItem;
}
}
}
#if CORECLR
// Check for low-priority work items
if (s_prioritizationExperiment && lowPriorityWorkItems.TryDequeue(out workItem))
{
return workItem;
}
#endif
// Try to steal from other threads' local work items
{
WorkStealingQueue localWsq = tl.workStealingQueue;
WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
int c = queues.Length;
Debug.Assert(c > 0, "There must at least be a queue for this thread.");
int maxIndex = c - 1;
for (int i = (int)(randomValue % (uint)c); c > 0; i = i < maxIndex ? i + 1 : 0, c--)
{
WorkStealingQueue otherQueue = queues[i];
if (otherQueue != localWsq && otherQueue.CanSteal)
{
workItem = otherQueue.TrySteal(ref missedSteal);
if (workItem != null)
{
return workItem;
}
}
}
}
return null;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool TryStartProcessingHighPriorityWorkItemsAndDequeue(
ThreadPoolWorkQueueThreadLocals tl,
[MaybeNullWhen(false)] out object workItem)
{
Debug.Assert(!tl.isProcessingHighPriorityWorkItems);
if (!highPriorityWorkItems.TryDequeue(out workItem))
{
return false;
}
tl.isProcessingHighPriorityWorkItems = true;
_mayHaveHighPriorityWorkItems = true;
return true;
}
public static long LocalCount
{
get
{
long count = 0;
foreach (WorkStealingQueue workStealingQueue in WorkStealingQueueList.Queues)
{
count += workStealingQueue.Count;
}
return count;
}
}
public long GlobalCount
{
get
{
long count = (long)highPriorityWorkItems.Count + workItems.Count;
#if CORECLR
if (s_prioritizationExperiment)
{
count += lowPriorityWorkItems.Count;
}
#endif
for (int i = 0; i < s_assignableWorkItemQueueCount; i++)
{
count += _assignableWorkItemQueues[i].Count;
}
return count;
}
}
// Time in ms for which ThreadPoolWorkQueue.Dispatch keeps executing normal work items before either returning from
// Dispatch (if YieldFromDispatchLoop is true), or performing periodic activities
public const uint DispatchQuantumMs = 30;
private static object? DequeueWithPriorityAlternation(ThreadPoolWorkQueue workQueue, ThreadPoolWorkQueueThreadLocals tl, out bool missedSteal)
{
object? workItem = null;
// Alternate between checking for high-prioriy and normal-priority 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, when worker threads are continually starved,
// high-priority work items may always be queued and normal-priority work items may not get a chance to run.
bool dispatchNormalPriorityWorkFirst = workQueue._dispatchNormalPriorityWorkFirst;
if (dispatchNormalPriorityWorkFirst && !tl.workStealingQueue.CanSteal)
{
workQueue._dispatchNormalPriorityWorkFirst = !dispatchNormalPriorityWorkFirst;
WorkQueue queue =
s_assignableWorkItemQueueCount > 0 ? tl.assignedGlobalWorkItemQueue : workQueue.workItems;
if (!queue.TryDequeue(out workItem) && s_assignableWorkItemQueueCount > 0)
{
workQueue.workItems.TryDequeue(out workItem);
}
}
missedSteal = false;
workItem ??= workQueue.Dequeue(tl, ref missedSteal);
return workItem;
}
/// <summary>
/// Dispatches work items to this thread.
/// </summary>
/// <returns>
/// <c>true</c> if this thread did as much work as was available or its quantum expired.
/// <c>false</c> if this thread stopped working early.
/// </returns>
internal static bool Dispatch()
{
ThreadPoolWorkQueue workQueue = ThreadPool.s_workQueue;
ThreadPoolWorkQueueThreadLocals tl = workQueue.GetOrCreateThreadLocals();
if (s_assignableWorkItemQueueCount > 0)
{
workQueue.AssignWorkItemQueue(tl);
}
// The change needs to be visible to other threads that may request a worker thread before a work item is attempted
// to be dequeued by the current thread. In particular, if an enqueuer queues a work item and does not request a
// thread because it sees a Determining or Scheduled stage, and the current thread is the last thread processing
// work items, the current thread must either see the work item queued by the enqueuer, or it must see a stage of
// Scheduled, and try to dequeue again or request another thread.
Debug.Assert(workQueue._separated.queueProcessingStage == QueueProcessingStage.Scheduled);
workQueue._separated.queueProcessingStage = QueueProcessingStage.Determining;
Interlocked.MemoryBarrier();
object? workItem = null;
if (workQueue._nextWorkItemToProcess != null)
{
workItem = Interlocked.Exchange(ref workQueue._nextWorkItemToProcess, null);
}
if (workItem == null)
{
// Try to dequeue a work item, clean up and return if no item was found
while ((workItem = DequeueWithPriorityAlternation(workQueue, tl, out bool missedSteal)) == null)
{
//
// No work.
// If we missed a steal, though, there may be more work in the queue.
// Instead of looping around and trying again, we'll just request another thread. Hopefully the thread
// that owns the contended work-stealing queue will pick up its own workitems in the meantime,
// which will be more efficient than this thread doing it anyway.
//
if (missedSteal)
{
if (s_assignableWorkItemQueueCount > 0)
{
workQueue.UnassignWorkItemQueue(tl);
}
Debug.Assert(workQueue._separated.queueProcessingStage != QueueProcessingStage.NotScheduled);
workQueue._separated.queueProcessingStage = QueueProcessingStage.Scheduled;
ThreadPool.RequestWorkerThread();
return true;
}