summaryrefslogtreecommitdiff
path: root/src/vm/threadpoolrequest.cpp
blob: 523a0631d6097c6f887fc8d516f2bb0179fbbd28 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//=========================================================================

//
// ThreadPoolRequest.cpp
//

// 
// 
//=========================================================================

#include "common.h"
#include "comdelegate.h"
#include "comthreadpool.h"
#include "threadpoolrequest.h"
#include "win32threadpool.h"
#include "class.h"
#include "object.h"
#include "field.h"
#include "excep.h"
#include "eeconfig.h"
#include "corhost.h"
#include "nativeoverlapped.h"
#include "appdomain.inl"

BYTE PerAppDomainTPCountList::s_padding[MAX_CACHE_LINE_SIZE - sizeof(LONG)];
// Make this point to unmanaged TP in case, no appdomains have initialized yet.
// Cacheline aligned, hot variable
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG PerAppDomainTPCountList::s_ADHint = -1;

// Move out of from preceeding variables' cache line
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) UnManagedPerAppDomainTPCount PerAppDomainTPCountList::s_unmanagedTPCount;
//The list of all per-appdomain work-request counts.
ArrayListStatic PerAppDomainTPCountList::s_appDomainIndexList;

void PerAppDomainTPCountList::InitAppDomainIndexList()
{
    LIMITED_METHOD_CONTRACT;
    s_appDomainIndexList.Init();
}


//---------------------------------------------------------------------------
//AddNewTPIndex adds and returns a per-appdomain TP entry whenever a new appdomain 
//is created. Our list count should be equal to the max number of appdomains created 
//in the system.
//
//Assumptions:
//This function needs to be called under the SystemDomain lock. 
//The ArrayListStatic data dtructure allows traversing of the counts without a 
//lock, but addition to the list requires synchronization.
//
TPIndex PerAppDomainTPCountList::AddNewTPIndex()
{
    STANDARD_VM_CONTRACT;

    DWORD count = s_appDomainIndexList.GetCount();
    DWORD i = FindFirstFreeTpEntry();
    
    if (i == UNUSED_THREADPOOL_INDEX)
        i = count;

    TPIndex index(i+1);
    if(count > i) 
    {

        IPerAppDomainTPCount * pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(i));
        pAdCount->SetTPIndex(index);
        return index;
    }

#ifdef _MSC_VER
    // Disable this warning - we intentionally want __declspec(align()) to insert trailing padding for us
#pragma warning(disable:4316)  // Object allocated on the heap may not be aligned for this type.
#endif
    ManagedPerAppDomainTPCount * pAdCount = new ManagedPerAppDomainTPCount(index);
#ifdef _MSC_VER
#pragma warning(default:4316)  // Object allocated on the heap may not be aligned for this type.
#endif
    pAdCount->ResetState();

    IfFailThrow(s_appDomainIndexList.Append(pAdCount));

    return index;
}

DWORD PerAppDomainTPCountList::FindFirstFreeTpEntry()
{
   CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    DWORD DwnumADs = s_appDomainIndexList.GetCount();
    DWORD Dwi;
    IPerAppDomainTPCount * pAdCount;
    DWORD DwfreeIndex = UNUSED_THREADPOOL_INDEX;

    for (Dwi=0;Dwi < DwnumADs;Dwi++) 
    {
        pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(Dwi));
        _ASSERTE(pAdCount);
        
        if(pAdCount->IsTPIndexUnused()) 
        {
            DwfreeIndex = Dwi;  
            STRESS_LOG1(LF_THREADPOOL, LL_INFO1000, "FindFirstFreeTpEntry: reusing index %d\n", DwfreeIndex + 1);
            break;
        }    
    }

    return DwfreeIndex;
}


void PerAppDomainTPCountList::SetAppDomainId(TPIndex index, ADID id)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    IPerAppDomainTPCount * pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(index.m_dwIndex-1));

    //SetAppDomainID needs to be called after the PerDomainCount has been 
    //succesfully allocated for the appdomain.
    _ASSERTE(pAdCount);

    STRESS_LOG2(LF_THREADPOOL, LL_INFO1000, "SetAppDomainId: index %d id %d\n", index.m_dwIndex, id.m_dwId);
    pAdCount->SetAppDomainId(id);
}

//---------------------------------------------------------------------------
//ResetAppDomainIndex: Resets the  AppDomain ID  and the  per-appdomain 
//                     thread pool counts
//
//Arguments:
//index - The index into the s_appDomainIndexList for the AppDomain we're 
//        trying to clear (the AD being unloaded)
//
//Assumptions:
//This function needs to be called from the AD unload thread after all domain
//bound objects have been finalized when it's safe to recycle  the TPIndex. 
//ClearAppDomainRequestsActive can be called from this function because no 
// managed code is running (If managed code is running, this function needs 
//to be called under a managed per-appdomain lock).
//
void PerAppDomainTPCountList::ResetAppDomainIndex(TPIndex index)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    IPerAppDomainTPCount * pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(index.m_dwIndex-1));
    _ASSERTE(pAdCount);

    STRESS_LOG2(LF_THREADPOOL, LL_INFO1000, "ResetAppDomainIndex: index %d pAdCount %p\n", index.m_dwIndex, pAdCount);    

    pAdCount->ResetState();
    pAdCount->SetTPIndexUnused();
}

//---------------------------------------------------------------------------
//ResetAppDomainTPCounts: Resets the per-appdomain thread pool counts for a 
//                        given AppDomain.  Don't clear the ADID until we can
//                        safely recycle the TPIndex
//
//Arguments:
//index - The index into the s_appDomainIndexList for the AppDomain we're 
//        trying to clear
//
//Assumptions:
//This function needs to be called from the AD unload thread after we make sure
//that no more code is running in unmanaged code. ClearAppDomainRequestsActive
//can be called from this function because no managed code is running (If 
//managed code is running, this function needs to be called under a managed
//per-appdomain lock). 
//
void PerAppDomainTPCountList::ResetAppDomainTPCounts(TPIndex index)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    IPerAppDomainTPCount * pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(index.m_dwIndex-1));
    _ASSERTE(pAdCount);

    STRESS_LOG2(LF_THREADPOOL, LL_INFO1000, "ResetAppDomainTPCounts: index %d pAdCount %p\n", index.m_dwIndex, pAdCount);
    //Correct the thread pool counts, in case the appdomain was unloaded rudely.
    if(pAdCount->IsRequestPending()) 
    {
        ThreadpoolMgr::ClearAppDomainRequestsActive(FALSE, TRUE, (LONG)index.m_dwIndex);
    }
    
    pAdCount->ClearAppDomainRequestsActive(TRUE);
}

//---------------------------------------------------------------------------
//AreRequestsPendingInAnyAppDomains checks to see if there any requests pending
//in other appdomains. It also checks for pending unmanaged work requests. 
//This function is called at end of thread quantum to see if the thread needs to
//transition into a different appdomain. This function may also be called by
//the scheduler to check for any unscheduled work. 
//
bool PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
        SO_TOLERANT; //Its ok for tis function to fail.
    }
    CONTRACTL_END;

    DWORD DwnumADs = s_appDomainIndexList.GetCount();
    DWORD Dwi;
    IPerAppDomainTPCount * pAdCount;
    bool fRequestsPending = false;

    for (Dwi=0;Dwi < DwnumADs;Dwi++) 
    {

        pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(Dwi));
        _ASSERTE(pAdCount);
        
        if(pAdCount->IsRequestPending()) 
        {
            fRequestsPending = true;
            break;
        }    
    }   

    if(s_unmanagedTPCount.IsRequestPending()) 
    {
        fRequestsPending = true;
    }

    return fRequestsPending;
}


//---------------------------------------------------------------------------
//GetAppDomainIndexForThreadpoolDispatch is essentailly the 
//"AppDomain Scheduler". This function makes fairness/policy decisions as to
//which appdomain the thread needs to enter to. This function needs to guarantee
//that all appdomain work requests are processed fairly. At this time all
//appdomain requests and the unmanaged work requests are treated with the same 
//priority.
//
//Return Value:
//The appdomain ID in which to dispatch the worker thread,nmanaged work items
//need to be processed.
//
LONG PerAppDomainTPCountList::GetAppDomainIndexForThreadpoolDispatch()
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    LONG hint = s_ADHint;
    DWORD count = s_appDomainIndexList.GetCount();
    IPerAppDomainTPCount * pAdCount;
    DWORD Dwi;

     
    if (hint != -1) 
    {
        pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(hint));
    } 
    else 
    {
        pAdCount = &s_unmanagedTPCount;
    }

    //temphint ensures that the check for appdomains proceeds in a pure round robin fashion.
    LONG temphint = hint;

    _ASSERTE( pAdCount);

    if (pAdCount->TakeActiveRequest())
        goto HintDone;

    //If there is no work in any appdomains, check the unmanaged queue,
    hint = -1;

    for (Dwi=0;Dwi<count;Dwi++)
    {
        if (temphint == -1) 
        {
            temphint = 0; 
        }

        pAdCount = dac_cast<PTR_IPerAppDomainTPCount>(s_appDomainIndexList.Get(temphint));
        if (pAdCount->TakeActiveRequest())
        {
            hint = temphint;
            goto HintDone;
        }

        temphint++;

        _ASSERTE( temphint <= (LONG)count);

        if(temphint == (LONG)count)
        {
            temphint = 0; 
        }
    }   

    if (hint == -1 && !s_unmanagedTPCount.TakeActiveRequest())
    {
        //no work!
        return 0;
    }

HintDone:

    if((hint+1) < (LONG)count)
    {
         s_ADHint = hint+1;
    } 
    else 
    {
        s_ADHint = -1;
    }
    
    if (hint == -1) 
    {
        return hint;
    } 
    else 
    {
        return (hint+1);
    }
}


void UnManagedPerAppDomainTPCount::SetAppDomainRequestsActive()
{
    WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
    LONG count = VolatileLoad(&m_outstandingThreadRequestCount);
    while (count < (LONG)ThreadpoolMgr::NumberOfProcessors)
    {
        LONG prevCount = FastInterlockCompareExchange(&m_outstandingThreadRequestCount, count+1, count);
        if (prevCount == count)
        {
            ThreadpoolMgr::MaybeAddWorkingWorker();
            ThreadpoolMgr::EnsureGateThreadRunning();
            break;
        }
        count = prevCount;
    }
#endif
}

bool FORCEINLINE UnManagedPerAppDomainTPCount::TakeActiveRequest()
{
    LIMITED_METHOD_CONTRACT;
    LONG count = VolatileLoad(&m_outstandingThreadRequestCount);

    while (count > 0)
    {
        LONG prevCount = FastInterlockCompareExchange(&m_outstandingThreadRequestCount, count-1, count);
        if (prevCount == count)
            return true;
        count = prevCount;
    }

    return false;
}


FORCEINLINE void ReleaseWorkRequest(WorkRequest *workRequest) { ThreadpoolMgr::RecycleMemory( workRequest, ThreadpoolMgr::MEMTYPE_WorkRequest ); }
typedef Wrapper< WorkRequest *, DoNothing<WorkRequest *>, ReleaseWorkRequest > WorkRequestHolder;

void UnManagedPerAppDomainTPCount::QueueUnmanagedWorkRequest(LPTHREAD_START_ROUTINE  function, PVOID context)
{
    CONTRACTL
    {
        THROWS;     
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;;

#ifndef DACCESS_COMPILE    
    WorkRequestHolder pWorkRequest;

    //Note, ideally we would want to use our own queues instead of those in
    //the thread pool class. However, the queus in thread pool class have 
    //caching support, that shares memory with other commonly used structures
    //in the VM thread pool implementation. So, we decided to leverage those.

    pWorkRequest = ThreadpoolMgr::MakeWorkRequest(function, context);

    //MakeWorkRequest should throw if unable to allocate memory
    _ASSERTE(pWorkRequest != NULL);
    PREFIX_ASSUME(pWorkRequest != NULL);

    m_lock.Init(LOCK_TYPE_DEFAULT);
    
    {
        SpinLock::Holder slh(&m_lock);

        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, ThreadPoolEnqueue) && 
            !ThreadpoolMgr::AreEtwQueueEventsSpeciallyHandled(function))
            FireEtwThreadPoolEnqueue(pWorkRequest, GetClrInstanceId());
        ThreadpoolMgr::EnqueueWorkRequest(pWorkRequest);
        pWorkRequest.SuppressRelease();
        m_NumRequests++;
    }

    SetAppDomainRequestsActive();
#endif //DACCESS_COMPILE
}

PVOID UnManagedPerAppDomainTPCount::DeQueueUnManagedWorkRequest(bool* lastOne)
{
    CONTRACTL
    {
        NOTHROW;     
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;;

    *lastOne = true;

    WorkRequest * pWorkRequest = ThreadpoolMgr::DequeueWorkRequest();

    if (pWorkRequest) 
    {
        m_NumRequests--;

        if(m_NumRequests > 0) 
            *lastOne = false;
    }

    return (PVOID) pWorkRequest;
}

//---------------------------------------------------------------------------
//DispatchWorkItem manages dispatching of unmanaged work requests. It keeps
//processing unmanaged requests for the "Quanta". Essentially this function is 
//a tight loop of dequeueing unmanaged work requests and dispatching them.
//
void UnManagedPerAppDomainTPCount::DispatchWorkItem(bool* foundWork, bool* wasNotRecalled)
{
#ifndef DACCESS_COMPILE
    *foundWork = false;
    *wasNotRecalled = true;

    bool enableWorkerTracking = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking) ? true : false;

    DWORD startTime;
    DWORD endTime;
    
    startTime = GetTickCount();

    //For all practical puposes, the unmanaged part of thread pool is treated
    //as a special appdomain for thread pool purposes. The same logic as the 
    //one in managed code for dispatching thread pool requests is repeated here.
    //Namely we continue to process requests until eithere there are none, or
    //the "Quanta has expired". See threadpool.cs for the managed counterpart.

    WorkRequest * pWorkRequest=NULL;
    LPTHREAD_START_ROUTINE wrFunction;
    LPVOID wrContext;

    bool firstIteration = true;
    bool lastOne = false;

    while (*wasNotRecalled) 
    {
        m_lock.Init(LOCK_TYPE_DEFAULT);
        {
            SpinLock::Holder slh(&m_lock);
            pWorkRequest = (WorkRequest*) DeQueueUnManagedWorkRequest(&lastOne);
        }

        if (NULL == pWorkRequest)
            break;

        if (firstIteration && !lastOne)
            SetAppDomainRequestsActive();

        firstIteration = false;
        *foundWork = true;

        if (GCHeapUtilities::IsGCInProgress(TRUE))
        {
            // GC is imminent, so wait until GC is complete before executing next request.
            // this reduces in-flight objects allocated right before GC, easing the GC's work
            GCHeapUtilities::WaitForGCCompletion(TRUE);
        }

        PREFIX_ASSUME(pWorkRequest != NULL);
        _ASSERTE(pWorkRequest); 

        wrFunction = pWorkRequest->Function;
        wrContext  = pWorkRequest->Context;

        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, ThreadPoolDequeue) &&
            !ThreadpoolMgr::AreEtwQueueEventsSpeciallyHandled(wrFunction))
            FireEtwThreadPoolDequeue(pWorkRequest, GetClrInstanceId());

        ThreadpoolMgr::FreeWorkRequest(pWorkRequest);

        if (enableWorkerTracking)
        {
            ThreadpoolMgr::ReportThreadStatus(true);
            (wrFunction) (wrContext);
            ThreadpoolMgr::ReportThreadStatus(false);
        }
        else
        {
            (wrFunction) (wrContext);
        }

        ThreadpoolMgr::NotifyWorkItemCompleted();
        if (ThreadpoolMgr::ShouldAdjustMaxWorkersActive())
        {
            DangerousNonHostedSpinLockTryHolder tal(&ThreadpoolMgr::ThreadAdjustmentLock);
            if (tal.Acquired())
            {
                ThreadpoolMgr::AdjustMaxWorkersActive();
            }
            else
            {
                // the lock is held by someone else, so they will take care of this for us.
            }
        }
        *wasNotRecalled = ThreadpoolMgr::ShouldWorkerKeepRunning();

        Thread *pThread = GetThread();
        if (pThread) 
        {
            if (pThread->IsAbortRequested()) 
            {
                pThread->EEResetAbort(Thread::TAR_ALL);
            }
            pThread->InternalReset(FALSE);
        }

        endTime = GetTickCount();

        if ((endTime - startTime) >= TP_QUANTUM)
        {
           break;
        }
    }

    // if we're exiting for any reason other than the queue being empty, then we need to make sure another thread
    // will visit us later.
    if (NULL != pWorkRequest)
    {
        SetAppDomainRequestsActive();
    }

#endif //DACCESS_COMPILE
}


void ManagedPerAppDomainTPCount::SetAppDomainRequestsActive()
{
    //This function should either be called by managed code or during AD unload, but before
    //the TpIndex is set to unused.
    //
    // Note that there is a separate count in managed code that stays in sync with this one over time.
    // The manage count is incremented before this one, and this one is decremented before the managed
    // one.
    //

    _ASSERTE(m_index.m_dwIndex != UNUSED_THREADPOOL_INDEX);
    _ASSERTE(m_id.m_dwId != 0);

#ifndef DACCESS_COMPILE
        LONG count = VolatileLoad(&m_numRequestsPending);
        while (count != ADUnloading)
        {
            LONG prev = FastInterlockCompareExchange(&m_numRequestsPending, count+1, count);
            if (prev == count)
            {
                ThreadpoolMgr::MaybeAddWorkingWorker();
                ThreadpoolMgr::EnsureGateThreadRunning();
                break;
            }
            count = prev;
        }
#endif
}

void ManagedPerAppDomainTPCount::ClearAppDomainRequestsActive(BOOL bADU)
{
    LIMITED_METHOD_CONTRACT;
    //This function should either be called by managed code or during AD unload, but before
    //the TpIndex is set to unused.

    _ASSERTE(m_index.m_dwIndex != UNUSED_THREADPOOL_INDEX);
    _ASSERTE(m_id.m_dwId != 0);

    if (bADU)
    {
        VolatileStore(&m_numRequestsPending, ADUnloading);
    }
    else
    {
        LONG count = VolatileLoad(&m_numRequestsPending);
        // Test is: count > 0 && count != ADUnloading
        // Since:   const ADUnloading == -1
        // Both are tested: (count > 0) means following also true  (count != ADUnloading)
        while (count > 0)
        {
            LONG prev = FastInterlockCompareExchange(&m_numRequestsPending, 0, count);
            if (prev == count)
                break;
            count = prev;
        }
    }
}

bool ManagedPerAppDomainTPCount::TakeActiveRequest()
{
    LIMITED_METHOD_CONTRACT;
    LONG count = VolatileLoad(&m_numRequestsPending);
    // Test is: count > 0 && count != ADUnloading
    // Since:   const ADUnloading == -1
    // Both are tested: (count > 0) means following also true (count != ADUnloading)
    while (count > 0)
    {
        LONG prev = FastInterlockCompareExchange(&m_numRequestsPending, count-1, count);
        if (prev == count)
            return true;
        count = prev;
    }
    return false;
}

void ManagedPerAppDomainTPCount::ClearAppDomainUnloading()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

#ifndef DACCESS_COMPILE
    //
    // While the AD was trying to unload, we may have queued some work.  We would not
    // have added that work to this count, because the AD was unloading.  So we assume
    // here that we have work to do.
    //
    // We set this to NumberOfProcessors because that's the maximum count that the AD
    // might have tried to add.  It's OK for this count to be larger than the AD thinks
    // it should be, but if it's smaller then we will be permanently out of sync with the
    // AD.
    //
    VolatileStore(&m_numRequestsPending, (LONG)ThreadpoolMgr::NumberOfProcessors);
    if (ThreadpoolMgr::IsInitialized())
    {
        ThreadpoolMgr::MaybeAddWorkingWorker();
        ThreadpoolMgr::EnsureGateThreadRunning();
    }
#endif
}


#ifndef DACCESS_COMPILE

//---------------------------------------------------------------------------
//DispatchWorkItem makes sure the right exception handling frames are setup, 
//the thread is transitioned into the correct appdomain, and the right managed
//callback is called.
//
void ManagedPerAppDomainTPCount::DispatchWorkItem(bool* foundWork, bool* wasNotRecalled)
{
    *foundWork = false;
    *wasNotRecalled = true;

    HRESULT hr;
    Thread * pThread = GetThread();
    if (pThread == NULL)
    {
        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow(&hr);
        if (pThread == NULL) 
        {
            return;
        }
    }

    //We are in a state where AppDomain Unload has begun, but not all threads have been
    //forced out of the unloading domain. This check below will prevent us from getting
    //unmanaged AD unloaded exceptions while trying to enter an unloaded appdomain. 
    if (!IsAppDomainUnloading())
    {
        CONTRACTL
        {
            MODE_PREEMPTIVE;
            THROWS;
            GC_TRIGGERS;
        }
        CONTRACTL_END;

        GCX_COOP();
        BEGIN_SO_INTOLERANT_CODE(pThread);

        //
        // NOTE: there is a potential race between the time we retrieve the app 
        // domain pointer, and the time which this thread enters the domain.
        //
        // To solve the race, we rely on the fact that there is a thread sync (via 
        // GC) between releasing an app domain's handle, and destroying the 
        // app domain.  Thus it is important that we not go into preemptive gc mode
        // in that window.
        //

        {
            ADID appDomainId(m_id);

            // This TPIndex may have been recycled since we chose it for workitem dispatch.
            // Thus it's possible for the ADID we just read to refer to an AppDomain that's still
            // being created.  If so, the new AppDomain will necessarily have zero requests
            // pending (because the destruction of the previous AD that used this TPIndex
            // will have reset this object).  We don't want to call into such an AppDomain.
    // TODO: fix this another way!
    //        if (IsRequestPending())
            {
                ManagedThreadBase::ThreadPool(appDomainId, QueueUserWorkItemManagedCallback, wasNotRecalled);
            }

            if (pThread->IsAbortRequested())
            {
                // thread was aborted, and may not have had a chance to tell us it has work.
                ENTER_DOMAIN_ID(m_id)
                {
                    ThreadpoolMgr::SetAppDomainRequestsActive();
                    ThreadpoolMgr::QueueUserWorkItem(NULL,
                        NULL,
                        0,
                        FALSE);

                }
                END_DOMAIN_TRANSITION;
            }
        }

        // We should have released all locks.
        _ASSERTE(g_fEEShutDown || pThread->m_dwLockCount == 0 || pThread->m_fRudeAborted);

        END_SO_INTOLERANT_CODE;

        *foundWork = true;
    }
    else 
    {
        __SwitchToThread(0, CALLER_LIMITS_SPINNING);
        return;
    }
}

#endif // !DACCESS_COMPILE