Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
12 KiB

  1. //========= Copyright � 1996-2004, Valve LLC, All rights reserved. ============
  2. //
  3. // Purpose: A thread pool implementation. You give it CWorkItems,
  4. // it processes them asynchronously, and hands them back to you when they've
  5. // been completed.
  6. //
  7. // To declare a queue, provide the implementation of a CWorkItem subtype,
  8. // the thread name prefix for threads in the pool, and the number of work
  9. // threads you want.
  10. //
  11. // CNet uses this class to offload encryption to a separate thread,
  12. // so that's a good place to start looking for usage examples.
  13. //
  14. //=============================================================================
  15. #ifndef WORKTHREADPOOL_H
  16. #define WORKTHREADPOOL_H
  17. #ifdef _WIN32
  18. #pragma once
  19. #endif
  20. #include <refcount.h>
  21. #include <reliabletimer.h>
  22. #include "jobtime.h"
  23. // forward declaration for CTSQueue which we can't statically allocate as our member
  24. // because of alignment issues on Win64
  25. template <class T, bool bTestOptimizer >
  26. class CTSQueue;
  27. namespace GCSDK {
  28. // forward declarations
  29. class CWorkThread;
  30. class CJobMgr;
  31. // these functions return pointers to fixed string in the code section. We need this for VPROF nodes
  32. #define DECLARE_WORK_ITEM( classname ) \
  33. virtual const char* GetDispatchCompletedName() const { return #classname"::DispatchCompleted"; } \
  34. virtual const char* GetThreadProcessName() const { return #classname"::ThreadProcess"; }
  35. //-----------------------------------------------------------------------------
  36. // Purpose: Work item base class. Derive from this for specific work item types.
  37. // The derived type ideally should be self-contained with all data it
  38. // needs to perform the work.
  39. //-----------------------------------------------------------------------------
  40. class CWorkItem : public CRefCount
  41. {
  42. public:
  43. CWorkItem()
  44. : m_JobID( k_GIDNil ),
  45. m_bRunning( false ),
  46. m_bResubmit( false ),
  47. m_bCanceled( false ),
  48. m_ulSequenceNumber( 0 )
  49. {
  50. m_jobtimeTimeout.SetLTime( 0 );
  51. m_jobtimeQueued.SetToJobTime();
  52. }
  53. CWorkItem( JobID_t jobID )
  54. : m_JobID( jobID ),
  55. m_bRunning( false ),
  56. m_bResubmit( false ),
  57. m_bCanceled( false ),
  58. m_ulSequenceNumber( 0 )
  59. {
  60. m_jobtimeTimeout.SetLTime( 0 );
  61. m_jobtimeQueued.SetToJobTime();
  62. }
  63. CWorkItem( JobID_t jobID, int64 cTimeoutMicroseconds )
  64. : m_JobID( jobID ),
  65. m_bRunning( false ),
  66. m_bResubmit( false ),
  67. m_bCanceled( false ),
  68. m_ulSequenceNumber( 0 )
  69. {
  70. SetPreExecuteTimeout( cTimeoutMicroseconds );
  71. m_jobtimeQueued.SetToJobTime();
  72. }
  73. void SetJobID( JobID_t jobID )
  74. {
  75. Assert(jobID != k_GIDNil) ;
  76. m_JobID = jobID;
  77. }
  78. JobID_t GetJobID() const { return m_JobID; }
  79. bool HasTimedOut() const { return m_jobtimeTimeout.LTime() != 0 && m_jobtimeTimeout.CServerMicroSecsPassed() > 0; }
  80. int64 WaitingTime() const { return m_jobtimeQueued.CServerMicroSecsPassed(); }
  81. void SetPreExecuteTimeout( int64 cMicroSeconds ) { m_jobtimeTimeout.SetFromJobTime( cMicroSeconds ); }
  82. bool BPreExecuteTimeoutSet( ) const { return m_jobtimeTimeout.LTime() != 0; }
  83. void ForceTimeOut() { m_jobtimeTimeout.SetFromJobTime( -1 );}
  84. bool BIsRunning() const { return m_bRunning; } // true if running right now
  85. bool WasCancelled() const { return m_bCanceled; }
  86. void SetCycleCount( CCycleCount& cycleCount ) { m_CycleCount = cycleCount ; }
  87. CCycleCount GetCycleCount() { return m_CycleCount; }
  88. uint64 GetSequenceNumber() { return m_ulSequenceNumber; }
  89. // Work threads can call this to force a work item to be reprocessed (added to the end of the process queue)
  90. void SetResubmit( bool bResubmit ) { m_bResubmit = bResubmit; }
  91. // these functions return pointers to fixed string in the code section.
  92. // We need this for VPROF nodes, you must use the DECLARE_WORK_ITEM macro
  93. virtual const char* GetDispatchCompletedName() const = 0;
  94. virtual const char* GetThreadProcessName() const = 0;
  95. // Return false if your operation failed in some way that you would want to know about
  96. // The CWorkThreadPool will count the failures.
  97. virtual bool ThreadProcess( CWorkThread *pThread ) = 0; // called by the worker thread
  98. virtual bool DispatchCompletedWorkItem( CJobMgr *jobMgr ); // called by main loop after item completed
  99. protected:
  100. // note: destructor is private. This is a ref-counted object, private destructor ensures callers can't accidentally delete
  101. // directly, or declare on stack
  102. virtual ~CWorkItem() { }
  103. friend class CWorkThread;
  104. friend class CWorkThreadPool;
  105. uint64 m_ulSequenceNumber; // Sequence number for the work item, used when enforcing output ordering as matching input order
  106. CCycleCount m_CycleCount; // A record of how long it took to execute this particular work item !
  107. private:
  108. bool m_bResubmit; // true if the item should be resubmitted after last run
  109. volatile bool m_bRunning; // true if the work item is running right now
  110. bool m_bCanceled; // true if the work was canceled due to timeout
  111. CJobTime m_jobtimeTimeout; // time at which this result is no longer valid, so it shouldn't start to be processed
  112. CJobTime m_jobtimeQueued;
  113. JobID_t m_JobID;
  114. };
  115. // forward decl
  116. class CWorkThreadPool;
  117. //-----------------------------------------------------------------------------
  118. // Purpose: Generic work thread implementation, to be specialized if necessary
  119. //-----------------------------------------------------------------------------
  120. class CWorkThread : public CThread
  121. {
  122. public:
  123. CWorkThread( CWorkThreadPool *pThreadPool );
  124. CWorkThread( CWorkThreadPool *pThreadPool, const char *pszName );
  125. virtual ~CWorkThread()
  126. {
  127. }
  128. virtual int Run();
  129. virtual void Cancel()
  130. {
  131. }
  132. protected:
  133. CWorkThreadPool *m_pThreadPool; // parent pool
  134. volatile bool m_bExitThread; // set by CWorkThreadPool::StopWorkerThreads and possibly by subclasses of CWorkThread
  135. volatile bool m_bFinished; // set by CWorkThread::Run [note: must still check IsThreadRunning, and/or call Join]
  136. virtual void OnStart() { }
  137. virtual void OnExit() { }
  138. friend class CWorkThreadPool;
  139. };
  140. //-----------------------------------------------------------------------------
  141. // callback class to create work threads
  142. //-----------------------------------------------------------------------------
  143. class IWorkThreadFactory
  144. {
  145. public:
  146. virtual CWorkThread *CreateWorkerThread( class CWorkThreadPool *pWorkThreadPool ) = 0;
  147. };
  148. //-----------------------------------------------------------------------------
  149. // reusable trivial implementation of IWorkThreadFactory
  150. //-----------------------------------------------------------------------------
  151. template<class T>
  152. class CWorkThreadFactory : public IWorkThreadFactory
  153. {
  154. public:
  155. virtual CWorkThread *CreateWorkerThread( class CWorkThreadPool *pWorkThreadPool )
  156. {
  157. return new T( pWorkThreadPool );
  158. }
  159. };
  160. //-----------------------------------------------------------------------------
  161. // Purpose: interface class for object that the WorkThreadPool can signal when
  162. // there are completed work items to process
  163. //-----------------------------------------------------------------------------
  164. class IWorkThreadPoolSignal
  165. {
  166. public:
  167. virtual void Signal() = 0;
  168. };
  169. //-----------------------------------------------------------------------------
  170. // Purpose: pool of work threads.
  171. //-----------------------------------------------------------------------------
  172. class CWorkThreadPool
  173. {
  174. friend class CWorkThread;
  175. public:
  176. static void SetWorkItemCompletedSignal( IWorkThreadPoolSignal *pObject )
  177. {
  178. sm_pWorkItemsCompletedSignal = pObject;
  179. }
  180. CWorkThreadPool( const char *pszThreadNamePfx );
  181. // eventually it might be nice to be able to resize these pools via console command
  182. // in that case, we'd want a constructor like this, and a PoolSize accessor/mutator pair
  183. // it makes this class much more complicated, however (growing the pool is easy, shrinking it
  184. // is less easy) so we'll punt for now.
  185. /* CWorkThreadPool( const char *pszName = "unnamed thread" ) : CWorkThreadPool( pszName, -1 ); */
  186. virtual ~CWorkThreadPool();
  187. // Setting this will ensure that items of the same priority complete and get dispatched in the same order
  188. // they are added to the threadpool. This has a small additional locking overhead and can increase latency
  189. // as items that are actually completed out-of-order have to queue waiting on earlier items.
  190. void SetEnsureOutputOrdering( bool bEnsureOutputOrdering ) { m_bEnsureOutputOrdering = bEnsureOutputOrdering; }
  191. void AllowTimeouts( bool bMayHaveJobTimeouts ) { m_bMayHaveJobTimeouts = bMayHaveJobTimeouts; }
  192. int AddWorkThread( CWorkThread *pThread );
  193. void StartWorkThreads(); // gentlemen, start your engines
  194. void StopWorkThreads(); // stop work threads
  195. bool HasWorkItemsToProcess() const;
  196. // sets it to use dynamic worker thread construction
  197. // if pWorkThreadControl is NULL, just creates a standard CWorkThread object
  198. void SetWorkThreadAutoConstruct( int cMaxThreads, IWorkThreadFactory *pWorkThreadConstructor );
  199. bool AddWorkItem( CWorkItem *pWorkItem ); // add a work item to the queue to process
  200. CWorkItem *GetNextCompletedWorkItem( ); // get next completed work item and it's priority if needed
  201. const char *GetThreadNamePrefix() const { return m_szThreadNamePfx; }
  202. void SetNeverSetEventOnAdd( bool bNeverSet );
  203. bool BNeverSetEventOnAdd() { return m_bNeverSetOnAdd; }
  204. // get count of completed work items
  205. // can't be inline because of m_TSQueueCompleted type
  206. int GetCompletedWorkItemCount() const;
  207. // get count of work items to process
  208. // can't be inline because of m_TSQueueToProcess type
  209. int GetWorkItemToProcessCount() const;
  210. uint64 GetLastUsedSequenceNumber( ) const
  211. {
  212. return m_ulLastUsedSequenceNumber;
  213. }
  214. uint64 GetLastCompletedSequenceNumber( ) const
  215. {
  216. return m_ulLastCompletedSequenceNumber;
  217. }
  218. uint64 GetLastDispatchedSequenceNumber( ) const
  219. {
  220. return m_ulLastDispatchedSequenceNumber;
  221. }
  222. #if 0
  223. uint64 GetAveExecutionTime() const
  224. {
  225. return m_StatExecutionTime.GetUlAvg();
  226. }
  227. uint64 GetAveWaitTime() const
  228. {
  229. return m_StatWaitTime.GetUlAvg();
  230. }
  231. uint64 GetCurrentBacklogTime() const;
  232. #endif
  233. int CountCompletedSuccess() const { return m_cSuccesses; }
  234. int CountRetries() const { return m_cRetries; }
  235. int CountCompletedFailed() const { return m_cFailures; }
  236. bool BDispatchCompletedWorkItems( CLimitTimer &limitTimer, CJobMgr *pJobMgr );
  237. bool BExiting() const { return m_bExiting; }
  238. int GetWorkerCount() const { return m_WorkThreads.Count(); }
  239. uint GetActiveThreadCount() const { return m_cActiveThreads; }
  240. // make sure you lock before using this
  241. const CWorkThread *GetWorkThread( int iIndex ) const
  242. {
  243. Assert( iIndex >= 0 && iIndex < m_WorkThreads.Count() );
  244. return m_WorkThreads[iIndex];
  245. }
  246. protected:
  247. // STATICS
  248. static IWorkThreadPoolSignal *sm_pWorkItemsCompletedSignal;
  249. // MEMBERS
  250. CWorkItem *GetNextWorkItemToProcess( );
  251. void StartWorkThread( CWorkThread *pWorkThread, int iName );
  252. // meaningful thread name prefix
  253. char m_szThreadNamePfx[32];
  254. // have we actually initialized the threadpool?
  255. bool m_bThreadsInitialized;
  256. // Incoming queue: queue of all work items to process
  257. // must be dynamically allocated for alignment requirements on Win64
  258. CTSQueue< CWorkItem *, false > *m_pTSQueueToProcess;
  259. // Outgoing queues: queue of all completed work items
  260. // must be dynamically allocated for alignment requirements on Win64
  261. CTSQueue< CWorkItem *, false > *m_pTSQueueCompleted;
  262. // Vectors of completed, but out of order and waiting work items, only used when bEnsureOutputOrdering == true
  263. CThreadMutex m_MutexOnItemCompletedOrdered;
  264. CUtlVector< CWorkItem * > m_vecCompletedAndWaiting;
  265. // Should we emit work items in the same order they are received (on a per priority basis)
  266. bool m_bEnsureOutputOrdering;
  267. // Sequence numbers
  268. uint64 m_ulLastUsedSequenceNumber;
  269. uint64 m_ulLastCompletedSequenceNumber;
  270. uint64 m_ulLastDispatchedSequenceNumber;
  271. bool m_bMayHaveJobTimeouts;
  272. CUtlVector< CWorkThread * > m_WorkThreads;
  273. CThreadMutex m_WorkThreadMutex;
  274. CInterlockedUInt m_cThreadsRunning; // how many threads are running
  275. volatile bool m_bExiting; // are we exiting
  276. CThreadEvent m_EventNewWorkItem; // event set when a new work item is available to process
  277. CInterlockedInt m_cActiveThreads;
  278. volatile bool m_bNeverSetOnAdd;
  279. bool m_bAutoCreateThreads;
  280. int m_cMaxThreads;
  281. IWorkThreadFactory *m_pWorkThreadConstructor;
  282. // override this method if you want to do any special handling of completed work items. Default implementation puts
  283. // work items in our completed item queue.
  284. virtual void OnWorkItemCompleted( CWorkItem *pWorkItem );
  285. bool BTryDeleteExitedWorkerThreads();
  286. int m_cSuccesses;
  287. int m_cFailures;
  288. int m_cRetries;
  289. #if 0
  290. CStat m_StatExecutionTime;
  291. CStat m_StatWaitTime;
  292. #endif
  293. CLimitTimer m_LimitTimerCreateNewThreads;
  294. };
  295. } // namespace GCSDK
  296. #endif // WORKTHREAD_H