forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjobthread.cpp
1441 lines (1236 loc) · 33 KB
/
jobthread.cpp
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#if defined( _WIN32 ) && !defined( _X360 )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "tier0/dbg.h"
#include "tier0/tslist.h"
#include "tier0/icommandline.h"
#include "vstdlib/jobthread.h"
#include "vstdlib/random.h"
#include "tier1/functors.h"
#include "tier1/fmtstr.h"
#include "tier1/utlvector.h"
#include "tier1/generichash.h"
#include "tier0/vprof.h"
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
#include "tier0/memdbgon.h"
class CJobThread;
//-----------------------------------------------------------------------------
inline void ServiceJobAndRelease( CJob *pJob, int iThread = -1 )
{
// TryLock() would only fail if another thread has entered
// Execute() or Abort()
if ( !pJob->IsFinished() && pJob->TryLock() )
{
// ...service the request
pJob->SetServiceThread( iThread );
pJob->Execute();
pJob->Unlock();
}
pJob->Release();
}
//-----------------------------------------------------------------------------
class ALIGN16 CJobQueue
{
public:
CJobQueue() :
m_nItems( 0 ),
m_nMaxItems( INT_MAX )
{
for ( int i = 0; i < ARRAYSIZE( m_pQueues ); i++ )
{
m_pQueues[i] = new CTSQueue<CJob *>;
}
}
~CJobQueue()
{
for ( int i = 0; i < ARRAYSIZE( m_pQueues ); i++ )
{
delete m_pQueues[i];
}
}
int Count()
{
return m_nItems;
}
int Count( JobPriority_t priority )
{
return m_pQueues[priority]->Count();
}
CJob *PrePush()
{
if ( m_nItems >= m_nMaxItems )
{
CJob *pOverflowJob;
if ( Pop( &pOverflowJob ) )
{
return pOverflowJob;
}
}
return NULL;
}
int Push( CJob *pJob, int iThread = -1 )
{
pJob->AddRef();
CJob *pOverflowJob;
int nOverflow = 0;
while ( ( pOverflowJob = PrePush() ) != NULL )
{
ServiceJobAndRelease( pJob );
nOverflow++;
}
m_pQueues[pJob->GetPriority()]->PushItem( pJob );
m_mutex.Lock();
if ( ++m_nItems == 1 )
{
m_JobAvailableEvent.Set();
}
m_mutex.Unlock();
return nOverflow;
}
bool Pop( CJob **ppJob )
{
m_mutex.Lock();
if ( !m_nItems )
{
m_mutex.Unlock();
*ppJob = NULL;
return false;
}
if ( --m_nItems == 0 )
{
m_JobAvailableEvent.Reset();
}
m_mutex.Unlock();
for ( int i = JP_HIGH; i >= 0; --i )
{
if ( m_pQueues[i]->PopItem( ppJob ) )
{
return true;
}
}
AssertMsg( 0, "Expected at least one queue item" );
*ppJob = NULL;
return false;
}
CThreadEvent &GetEventHandle()
{
return m_JobAvailableEvent;
}
void Flush()
{
// Only safe to call when system is suspended
m_mutex.Lock();
m_nItems = 0;
m_JobAvailableEvent.Reset();
CJob *pJob;
for ( int i = JP_HIGH; i >= 0; --i )
{
while ( m_pQueues[i]->PopItem( &pJob ) )
{
pJob->Abort();
pJob->Release();
}
}
m_mutex.Unlock();
}
private:
CTSQueue<CJob *> *m_pQueues[JP_HIGH + 1];
int m_nItems;
int m_nMaxItems;
CThreadMutex m_mutex;
CThreadManualEvent m_JobAvailableEvent;
} ALIGN16_POST;
//-----------------------------------------------------------------------------
//
// CThreadPool
//
//-----------------------------------------------------------------------------
class CThreadPool : public CRefCounted1<IThreadPool, CRefCountServiceMT>
{
public:
CThreadPool();
~CThreadPool();
//-----------------------------------------------------
// Thread functions
//-----------------------------------------------------
bool Start( const ThreadPoolStartParams_t &startParams = ThreadPoolStartParams_t() ) { return Start( startParams, NULL ); }
bool Start( const ThreadPoolStartParams_t &startParams, const char *pszNameOverride );
bool Stop( int timeout = TT_INFINITE );
void Distribute( bool bDistribute = true, int *pAffinityTable = NULL );
//-----------------------------------------------------
// Functions for any thread
//-----------------------------------------------------
unsigned GetJobCount() { return m_nJobs; }
int NumThreads();
int NumIdleThreads();
//-----------------------------------------------------
// Pause/resume processing jobs
//-----------------------------------------------------
int SuspendExecution();
int ResumeExecution();
//-----------------------------------------------------
// Offer the current thread to the pool
//-----------------------------------------------------
virtual int YieldWait( CThreadEvent **pEvents, int nEvents, bool bWaitAll = true, unsigned timeout = TT_INFINITE );
virtual int YieldWait( CJob **, int nJobs, bool bWaitAll = true, unsigned timeout = TT_INFINITE );
inline void Yield( unsigned timeout )
{
Assert( ThreadInMainThread() );
ThreadSleep( timeout );
}
//-----------------------------------------------------
// Add a native job to the queue (master thread)
//-----------------------------------------------------
void AddJob( CJob * );
void InsertJobInQueue( CJob * );
//-----------------------------------------------------
// All threads execute pFunctor asap. Thread will either wake up
// and execute or execute pFunctor right after completing current job and
// before looking for another job.
//-----------------------------------------------------
// void ExecuteHighPriorityFunctor( CFunctor *pFunctor );
//-----------------------------------------------------
// Add an function object to the queue (master thread)
//-----------------------------------------------------
void AddFunctorInternal( CFunctor *, CJob ** = NULL, const char *pszDescription = NULL, unsigned flags = 0 );
//-----------------------------------------------------
// Remove a job from the queue (master thread)
//-----------------------------------------------------
virtual void ChangePriority( CJob *p, JobPriority_t priority );
//-----------------------------------------------------
// Bulk job manipulation (blocking)
//-----------------------------------------------------
int ExecuteToPriority( JobPriority_t toPriority, JobFilter_t pfnFilter = NULL );
int AbortAll();
virtual void Reserved1() {}
private:
enum
{
IO_STACKSIZE = ( 64 * 1024 ),
COMPUTATION_STACKSIZE = 0,
};
//-----------------------------------------------------
//
//-----------------------------------------------------
CJob *PeekJob();
CJob *GetDummyJob();
//-----------------------------------------------------
// Thread functions
//-----------------------------------------------------
int Run();
private:
friend class CJobThread;
CJobQueue m_SharedQueue;
CInterlockedInt m_nIdleThreads;
CUtlVector<CJobThread *> m_Threads;
CUtlVector<CThreadEvent *> m_IdleEvents;
CThreadMutex m_SuspendMutex;
int m_nSuspend;
CInterlockedInt m_nJobs;
// Some jobs should only be executed on the threadpool thread(s). Ie: the rendering thread has the GL context
// and the main thread coming in and "helping" with jobs breaks that pretty nicely. This flag states that
// only the threadpool threads should execute these jobs.
bool m_bExecOnThreadPoolThreadsOnly;
};
//-----------------------------------------------------------------------------
JOB_INTERFACE IThreadPool *CreateThreadPool()
{
return new CThreadPool;
}
JOB_INTERFACE void DestroyThreadPool( IThreadPool *pPool )
{
delete pPool;
}
//-----------------------------------------------------------------------------
class CGlobalThreadPool : public CThreadPool
{
public:
virtual bool Start( const ThreadPoolStartParams_t &startParamsIn )
{
int nThreads = ( CommandLine()->ParmValue( "-threads", -1 ) - 1 );
ThreadPoolStartParams_t startParams = startParamsIn;
if ( nThreads >= 0 )
{
startParams.nThreads = nThreads;
}
else
{
// Cap the GlobPool threads at 4.
startParams.nThreadsMax = 4;
}
return CThreadPool::Start( startParams, "Glob" );
}
virtual bool OnFinalRelease()
{
AssertMsg( 0, "Releasing global thread pool object!" );
return false;
}
};
//-----------------------------------------------------------------------------
class CJobThread : public CWorkerThread
{
public:
CJobThread( CThreadPool *pOwner, int iThread ) :
m_SharedQueue( pOwner->m_SharedQueue ),
m_pOwner( pOwner ),
m_iThread( iThread )
{
}
CThreadEvent &GetIdleEvent()
{
return m_IdleEvent;
}
CJobQueue &AccessDirectQueue()
{
return m_DirectQueue;
}
private:
unsigned Wait()
{
unsigned waitResult;
tmZone( TELEMETRY_LEVEL0, TMZF_IDLE, "%s", __FUNCTION__ );
#ifdef WIN32
enum Event_t
{
CALL_FROM_MASTER,
SHARED_QUEUE,
DIRECT_QUEUE,
NUM_EVENTS
};
HANDLE waitHandles[NUM_EVENTS];
waitHandles[CALL_FROM_MASTER] = GetCallHandle().GetHandle();
waitHandles[SHARED_QUEUE] = m_SharedQueue.GetEventHandle().GetHandle();
waitHandles[DIRECT_QUEUE] = m_DirectQueue.GetEventHandle().GetHandle();
#ifdef _DEBUG
while ( ( waitResult = WaitForMultipleObjects( ARRAYSIZE(waitHandles), waitHandles, FALSE, 10 ) ) == WAIT_TIMEOUT )
{
waitResult = waitResult; // break here
}
#else
waitResult = WaitForMultipleObjects( ARRAYSIZE(waitHandles), waitHandles, FALSE, INFINITE );
#endif
#else // !win32
bool bSet = false;
int nWaitTime = 100;
while( !bSet )
{
// Jobs are typically enqueued to the shared job queue so wait on it first.
bSet = m_SharedQueue.GetEventHandle().Wait( nWaitTime );
if( !bSet )
bSet = m_DirectQueue.GetEventHandle().Wait( 10 );
if ( !bSet )
bSet = GetCallHandle().Wait( 0 );
}
if ( !bSet )
waitResult = WAIT_TIMEOUT;
else
waitResult = WAIT_OBJECT_0;
#endif
return waitResult;
}
int Run()
{
// Wait for either a call from the master thread, or an item in the queue...
unsigned waitResult;
bool bExit = false;
tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );
m_pOwner->m_nIdleThreads++;
m_IdleEvent.Set();
while (!bExit && ( ( waitResult = Wait() ) != WAIT_FAILED ) )
{
if ( PeekCall() )
{
CFunctor *pFunctor = NULL;
tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s PeekCall():%d", __FUNCTION__, GetCallParam() );
switch ( GetCallParam() )
{
case TPM_EXIT:
Reply( true );
bExit = TRUE;
break;
case TPM_SUSPEND:
Reply( true );
Suspend();
break;
/* case TPM_RUNFUNCTOR:
if( pFunctor )
{
( *pFunctor )();
Reply( true );
}
else
{
Assert( pFunctor );
Reply( false );
}
break;*/
default:
AssertMsg( 0, "Unknown call to thread" );
Reply( false );
break;
}
}
else
{
tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s !PeekCall()", __FUNCTION__ );
CJob *pJob;
bool bTookJob = false;
do
{
if ( !m_DirectQueue.Pop( &pJob) )
{
if ( !m_SharedQueue.Pop( &pJob ) )
{
// Nothing to process, return to wait state
break;
}
}
if ( !bTookJob )
{
m_IdleEvent.Reset();
m_pOwner->m_nIdleThreads--;
bTookJob = true;
}
ServiceJobAndRelease( pJob, m_iThread );
m_pOwner->m_nJobs--;
} while ( !PeekCall() );
if ( bTookJob )
{
m_pOwner->m_nIdleThreads++;
m_IdleEvent.Set();
}
}
}
m_pOwner->m_nIdleThreads--;
m_IdleEvent.Reset();
return 0;
}
CJobQueue m_DirectQueue;
CJobQueue & m_SharedQueue;
CThreadPool * m_pOwner;
CThreadManualEvent m_IdleEvent;
int m_iThread;
};
//-----------------------------------------------------------------------------
CGlobalThreadPool g_ThreadPool;
IThreadPool *g_pThreadPool = &g_ThreadPool;
//-----------------------------------------------------------------------------
//
// CThreadPool
//
//-----------------------------------------------------------------------------
CThreadPool::CThreadPool() :
m_nIdleThreads( 0 ),
m_nJobs( 0 ),
m_nSuspend( 0 )
{
}
//---------------------------------------------------------
CThreadPool::~CThreadPool()
{
Stop();
}
//---------------------------------------------------------
//
//---------------------------------------------------------
int CThreadPool::NumThreads()
{
return m_Threads.Count();
}
//---------------------------------------------------------
//
//---------------------------------------------------------
int CThreadPool::NumIdleThreads()
{
return m_nIdleThreads;
}
/*void CThreadPool::ExecuteHighPriorityFunctor( CFunctor *pFunctor )
{
int i;
for ( i = 0; i < m_Threads.Count(); i++ )
{
m_Threads[i]->CallWorker( TPM_RUNFUNCTOR, 0, false, pFunctor );
}
for ( i = 0; i < m_Threads.Count(); i++ )
{
m_Threads[i]->WaitForReply();
}
}*/
//---------------------------------------------------------
// Pause/resume processing jobs
//---------------------------------------------------------
int CThreadPool::SuspendExecution()
{
AUTO_LOCK( m_SuspendMutex );
// If not already suspended
if ( m_nSuspend == 0 )
{
// Make sure state is correct
int i;
for ( i = 0; i < m_Threads.Count(); i++ )
{
m_Threads[i]->CallWorker( TPM_SUSPEND, 0 );
}
for ( i = 0; i < m_Threads.Count(); i++ )
{
m_Threads[i]->WaitForReply();
}
// Because worker must signal before suspending, we could reach
// here with the thread not actually suspended
for ( i = 0; i < m_Threads.Count(); i++ )
{
while ( !m_Threads[i]->IsSuspended() )
{
ThreadSleep();
}
}
}
return m_nSuspend++;
}
//---------------------------------------------------------
int CThreadPool::ResumeExecution()
{
AUTO_LOCK( m_SuspendMutex );
AssertMsg( m_nSuspend >= 1, "Attempted resume when not suspended");
int result = m_nSuspend--;
if (m_nSuspend == 0 )
{
for ( int i = 0; i < m_Threads.Count(); i++ )
{
m_Threads[i]->Resume();
}
}
return result;
}
//---------------------------------------------------------
int CThreadPool::YieldWait( CThreadEvent **pEvents, int nEvents, bool bWaitAll, unsigned timeout )
{
tmZone( TELEMETRY_LEVEL0, TMZF_IDLE, "%s(%d) SPINNING %t", __FUNCTION__, timeout, tmSendCallStack( TELEMETRY_LEVEL0, 0 ) );
Assert( timeout == TT_INFINITE ); // unimplemented
int result;
CJob *pJob;
// Always wait for zero milliseconds initially, to let us process jobs on this thread.
timeout = 0;
while ( ( result = CThreadEvent::WaitForMultiple( nEvents, pEvents, bWaitAll, timeout ) ) == TW_TIMEOUT )
{
if ( !m_bExecOnThreadPoolThreadsOnly && m_SharedQueue.Pop( &pJob ) )
{
ServiceJobAndRelease( pJob );
m_nJobs--;
}
else
{
// Since there are no jobs for the main thread set the timeout to infinite.
// The only disadvantage to this is that if a job thread creates a new job
// then the main thread will not be available to pick it up, but if that
// is a problem you can just create more worker threads. Debugging test runs
// of TF2 suggests that jobs are only ever added from the main thread which
// means that there is no disadvantage.
// Waiting on the events instead of busy spinning has multiple advantages.
// It avoids wasting CPU time/electricity, it makes it more obvious in profiles
// when the main thread is idle versus busy, and it allows ready thread analysis
// in xperf to find out what woke up a waiting thread.
// It also avoids unnecessary CPU starvation -- seen on customer traces of TF2.
timeout = TT_INFINITE;
}
}
return result;
}
//---------------------------------------------------------
int CThreadPool::YieldWait( CJob **ppJobs, int nJobs, bool bWaitAll, unsigned timeout )
{
CUtlVectorFixed<CThreadEvent *, 64> handles;
if ( nJobs > handles.NumAllocated() - 2 )
{
return TW_FAILED;
}
for ( int i = 0; i < nJobs; i++ )
{
handles.AddToTail( ppJobs[i]->AccessEvent() );
}
return YieldWait( handles.Base(), handles.Count(), bWaitAll, timeout);
}
//---------------------------------------------------------
// Add a job to the queue
//---------------------------------------------------------
void CThreadPool::AddJob( CJob *pJob )
{
if ( !pJob )
{
return;
}
if ( pJob->m_ThreadPoolData != JOB_NO_DATA )
{
Warning( "Cannot add a thread job already committed to another thread pool\n" );
return;
}
if ( m_Threads.Count() == 0 )
{
// So only threadpool jobs are supposed to execute the jobs, but there are no threadpool threads?
Assert( !m_bExecOnThreadPoolThreadsOnly );
pJob->Execute();
return;
}
int flags = pJob->GetFlags();
if ( !m_bExecOnThreadPoolThreadsOnly && ( ( flags & ( JF_IO | JF_QUEUE ) ) == 0 ) /* @TBD && !m_queue.Count() */ )
{
if ( !NumIdleThreads() )
{
pJob->Execute();
return;
}
pJob->SetPriority( JP_HIGH );
}
if ( !pJob->CanExecute() )
{
// Already handled
ExecuteOnce( Warning( "Attempted to add job to job queue that has already been completed\n" ) );
return;
}
pJob->m_pThreadPool = this;
pJob->m_status = JOB_STATUS_PENDING;
InsertJobInQueue( pJob );
++m_nJobs;
}
//---------------------------------------------------------
//
//---------------------------------------------------------
void CThreadPool::InsertJobInQueue( CJob *pJob )
{
CJobQueue *pQueue;
if ( !( pJob->GetFlags() & JF_SERIAL ) )
{
int iThread = pJob->GetServiceThread();
if ( iThread == -1 || !m_Threads.IsValidIndex( iThread ) )
{
pQueue = &m_SharedQueue;
}
else
{
pQueue = &(m_Threads[iThread]->AccessDirectQueue());
}
}
else
{
pQueue = &(m_Threads[0]->AccessDirectQueue());
}
m_nJobs -= pQueue->Push( pJob );
}
//---------------------------------------------------------
// Add an function object to the queue (master thread)
//---------------------------------------------------------
void CThreadPool::AddFunctorInternal( CFunctor *pFunctor, CJob **ppJob, const char *pszDescription, unsigned flags )
{
// Note: assumes caller has handled refcount
CJob *pJob = new CFunctorJob( pFunctor, pszDescription );
pJob->SetFlags( flags );
AddJob( pJob );
if ( ppJob )
{
*ppJob = pJob;
}
else
{
pJob->Release();
}
}
//---------------------------------------------------------
// Remove a job from the queue
//---------------------------------------------------------
void CThreadPool::ChangePriority( CJob *pJob, JobPriority_t priority )
{
// Right now, only support upping the priority
if ( pJob->GetPriority() < priority )
{
pJob->SetPriority( priority );
m_SharedQueue.Push( pJob );
}
else
{
ExecuteOnce( if ( pJob->GetPriority() != priority ) DevMsg( "CThreadPool::RemoveJob not implemented right now" ) );
}
}
//---------------------------------------------------------
// Execute to a specified priority
//---------------------------------------------------------
int CThreadPool::ExecuteToPriority( JobPriority_t iToPriority, JobFilter_t pfnFilter )
{
SuspendExecution();
CJob *pJob;
int nExecuted = 0;
int i;
int nJobsTotal = GetJobCount();
CUtlVector<CJob *> jobsToPutBack;
for ( int iCurPriority = JP_HIGH; iCurPriority >= iToPriority; --iCurPriority )
{
for ( i = 0; i < m_Threads.Count(); i++ )
{
CJobQueue &queue = m_Threads[i]->AccessDirectQueue();
while ( queue.Count( (JobPriority_t)iCurPriority ) )
{
queue.Pop( &pJob );
if ( pfnFilter && !(*pfnFilter)( pJob ) )
{
if ( pJob->CanExecute() )
{
jobsToPutBack.EnsureCapacity( nJobsTotal );
jobsToPutBack.AddToTail( pJob );
}
else
{
m_nJobs--;
pJob->Release(); // an already serviced job in queue, may as well ditch it (as in, main thread probably force executed)
}
continue;
}
ServiceJobAndRelease( pJob );
m_nJobs--;
nExecuted++;
}
}
while ( m_SharedQueue.Count( (JobPriority_t)iCurPriority ) )
{
m_SharedQueue.Pop( &pJob );
if ( pfnFilter && !(*pfnFilter)( pJob ) )
{
if ( pJob->CanExecute() )
{
jobsToPutBack.EnsureCapacity( nJobsTotal );
jobsToPutBack.AddToTail( pJob );
}
else
{
m_nJobs--;
pJob->Release(); // see above
}
continue;
}
ServiceJobAndRelease( pJob );
m_nJobs--;
nExecuted++;
}
}
for ( i = 0; i < jobsToPutBack.Count(); i++ )
{
InsertJobInQueue( jobsToPutBack[i] );
jobsToPutBack[i]->Release();
}
ResumeExecution();
return nExecuted;
}
//---------------------------------------------------------
//
//---------------------------------------------------------
int CThreadPool::AbortAll()
{
SuspendExecution();
CJob *pJob;
int iAborted = 0;
while ( m_SharedQueue.Pop( &pJob ) )
{
pJob->Abort();
pJob->Release();
iAborted++;
}
for ( int i = 0; i < m_Threads.Count(); i++ )
{
CJobQueue &queue = m_Threads[i]->AccessDirectQueue();
while ( queue.Pop( &pJob ) )
{
pJob->Abort();
pJob->Release();
iAborted++;
}
}
m_nJobs = 0;
ResumeExecution();
return iAborted;
}
//---------------------------------------------------------
// CThreadPool thread functions
//---------------------------------------------------------
bool CThreadPool::Start( const ThreadPoolStartParams_t &startParams, const char *pszName )
{
int nThreads = startParams.nThreads;
m_bExecOnThreadPoolThreadsOnly = startParams.bExecOnThreadPoolThreadsOnly;
if ( nThreads < 0 )
{
const CPUInformation &ci = *GetCPUInformation();
if ( startParams.bIOThreads )
{
nThreads = ci.m_nLogicalProcessors;
}
else
{
nThreads = ( ci.m_nLogicalProcessors / (( ci.m_bHT ) ? 2 : 1) ) - 1; // One per
if ( IsPC() )
{
if ( nThreads > 3 )
{
DevMsg( "Defaulting to limit of 3 worker threads, use -threads on command line if want more\n" ); // Current >4 processor configs don't really work so well, probably due to cache issues? (toml 7/12/2007)
nThreads = 3;
}
}
}
if ( ( startParams.nThreadsMax >= 0 ) && ( nThreads > startParams.nThreadsMax ) )
{
nThreads = startParams.nThreadsMax;
}
}
if ( nThreads <= 0 )
{
return true;
}
int nStackSize = startParams.nStackSize;
if ( nStackSize < 0 )
{
if ( startParams.bIOThreads )
{
nStackSize = IO_STACKSIZE;
}
else
{
nStackSize = COMPUTATION_STACKSIZE;
}
}
int priority = startParams.iThreadPriority;
if ( priority == SHRT_MIN )
{
if ( startParams.bIOThreads )
{
priority = THREAD_PRIORITY_HIGHEST;
}
else
{
priority = ThreadGetPriority();
}
}
bool bDistribute;
if ( startParams.fDistribute != TRS_NONE )
{
bDistribute = ( startParams.fDistribute == TRS_TRUE );
}
else
{
bDistribute = !startParams.bIOThreads;
}
//--------------------------------------------------------
m_Threads.EnsureCapacity( nThreads );
m_IdleEvents.EnsureCapacity( nThreads );
if ( !pszName )
{
pszName = ( startParams.bIOThreads ) ? "IOJobX" : "CmpJobX";
}
while ( nThreads-- )
{
int iThread = m_Threads.AddToTail();
m_IdleEvents.AddToTail();
m_Threads[iThread] = new CJobThread( this, iThread );
m_IdleEvents[iThread] = &m_Threads[iThread]->GetIdleEvent();
m_Threads[iThread]->SetName( CFmtStr( "%s%d", pszName, iThread ) );
m_Threads[iThread]->Start( nStackSize );
m_Threads[iThread]->GetIdleEvent().Wait();
#ifdef WIN32
ThreadSetPriority( (ThreadHandle_t)m_Threads[iThread]->GetThreadHandle(), priority );
#endif
}