Thread.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. ===========================================================================
  3. Doom 3 BFG Edition GPL Source Code
  4. Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
  5. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
  6. Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
  16. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
  17. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
  18. ===========================================================================
  19. */
  20. #ifndef __THREAD_H__
  21. #define __THREAD_H__
  22. /*
  23. ================================================
  24. idSysMutex provides a C++ wrapper to the low level system mutex functions. A mutex is an
  25. object that can only be locked by one thread at a time. It's used to prevent two threads
  26. from accessing the same piece of data simultaneously.
  27. ================================================
  28. */
  29. class idSysMutex {
  30. public:
  31. idSysMutex() { Sys_MutexCreate( handle ); }
  32. ~idSysMutex() { Sys_MutexDestroy( handle ); }
  33. bool Lock( bool blocking = true ) { return Sys_MutexLock( handle, blocking ); }
  34. void Unlock() { Sys_MutexUnlock( handle ); }
  35. private:
  36. mutexHandle_t handle;
  37. idSysMutex( const idSysMutex & s ) {}
  38. void operator=( const idSysMutex & s ) {}
  39. };
  40. /*
  41. ================================================
  42. idScopedCriticalSection is a helper class that automagically locks a mutex when it's created
  43. and unlocks it when it goes out of scope.
  44. ================================================
  45. */
  46. class idScopedCriticalSection {
  47. public:
  48. idScopedCriticalSection( idSysMutex & m ) : mutex(&m) { mutex->Lock(); }
  49. ~idScopedCriticalSection() { mutex->Unlock(); }
  50. private:
  51. idSysMutex * mutex; // NOTE: making this a reference causes a TypeInfo crash
  52. };
  53. /*
  54. ================================================
  55. idSysSignal is a C++ wrapper for the low level system signal functions. A signal is an object
  56. that a thread can wait on for it to be raised. It's used to indicate data is available or that
  57. a thread has reached a specific point.
  58. ================================================
  59. */
  60. class idSysSignal {
  61. public:
  62. static const int WAIT_INFINITE = -1;
  63. idSysSignal( bool manualReset = false ) { Sys_SignalCreate( handle, manualReset ); }
  64. ~idSysSignal() { Sys_SignalDestroy( handle ); }
  65. void Raise() { Sys_SignalRaise( handle ); }
  66. void Clear() { Sys_SignalClear( handle ); }
  67. // Wait returns true if the object is in a signalled state and
  68. // returns false if the wait timed out. Wait also clears the signalled
  69. // state when the signalled state is reached within the time out period.
  70. bool Wait( int timeout = WAIT_INFINITE ) { return Sys_SignalWait( handle, timeout ); }
  71. private:
  72. signalHandle_t handle;
  73. idSysSignal( const idSysSignal & s ) {}
  74. void operator=( const idSysSignal & s ) {}
  75. };
  76. /*
  77. ================================================
  78. idSysInterlockedInteger is a C++ wrapper for the low level system interlocked integer
  79. routines to atomically increment or decrement an integer.
  80. ================================================
  81. */
  82. class idSysInterlockedInteger {
  83. public:
  84. idSysInterlockedInteger() : value( 0 ) {}
  85. // atomically increments the integer and returns the new value
  86. int Increment() { return Sys_InterlockedIncrement( value ); }
  87. // atomically decrements the integer and returns the new value
  88. int Decrement() { return Sys_InterlockedDecrement( value ); }
  89. // atomically adds a value to the integer and returns the new value
  90. int Add( int v ) { return Sys_InterlockedAdd( value, (interlockedInt_t) v ); }
  91. // atomically subtracts a value from the integer and returns the new value
  92. int Sub( int v ) { return Sys_InterlockedSub( value, (interlockedInt_t) v ); }
  93. // returns the current value of the integer
  94. int GetValue() const { return value; }
  95. // sets a new value, Note: this operation is not atomic
  96. void SetValue( int v ) { value = (interlockedInt_t)v; }
  97. private:
  98. interlockedInt_t value;
  99. };
  100. /*
  101. ================================================
  102. idSysInterlockedPointer is a C++ wrapper around the low level system interlocked pointer
  103. routine to atomically set a pointer while retrieving the previous value of the pointer.
  104. ================================================
  105. */
  106. template< typename T >
  107. class idSysInterlockedPointer {
  108. public:
  109. idSysInterlockedPointer() : ptr( NULL ) {}
  110. // atomically sets the pointer and returns the previous pointer value
  111. T * Set( T * newPtr ) {
  112. return (T *) Sys_InterlockedExchangePointer( (void * &) ptr, newPtr );
  113. }
  114. // atomically sets the pointer to 'newPtr' only if the previous pointer is equal to 'comparePtr'
  115. // ptr = ( ptr == comparePtr ) ? newPtr : ptr
  116. T * CompareExchange( T * comparePtr, T * newPtr ) {
  117. return (T *) Sys_InterlockedCompareExchangePointer( (void * &) ptr, comparePtr, newPtr );
  118. }
  119. // returns the current value of the pointer
  120. T * Get() const { return ptr; }
  121. private:
  122. T * ptr;
  123. };
  124. /*
  125. ================================================
  126. idSysThread is an abstract base class, to be extended by classes implementing the
  127. idSysThread::Run() method.
  128. class idMyThread : public idSysThread {
  129. public:
  130. virtual int Run() {
  131. // run thread code here
  132. return 0;
  133. }
  134. // specify thread data here
  135. };
  136. idMyThread thread;
  137. thread.Start( "myThread" );
  138. A worker thread is a thread that waits in place (without consuming CPU)
  139. until work is available. A worker thread is implemented as normal, except that, instead of
  140. calling the Start() method, the StartWorker() method is called to start the thread.
  141. Note that the Sys_CreateThread function does not support the concept of worker threads.
  142. class idMyWorkerThread : public idSysThread {
  143. public:
  144. virtual int Run() {
  145. // run thread code here
  146. return 0;
  147. }
  148. // specify thread data here
  149. };
  150. idMyWorkerThread thread;
  151. thread.StartThread( "myWorkerThread" );
  152. // main thread loop
  153. for ( ; ; ) {
  154. // setup work for the thread here (by modifying class data on the thread)
  155. thread.SignalWork(); // kick in the worker thread
  156. // run other code in the main thread here (in parallel with the worker thread)
  157. thread.WaitForThread(); // wait for the worker thread to finish
  158. // use results from worker thread here
  159. }
  160. In the above example, the thread does not continuously run in parallel with the main Thread,
  161. but only for a certain period of time in a very controlled manner. Work is set up for the
  162. Thread and then the thread is signalled to process that work while the main thread continues.
  163. After doing other work, the main thread can wait for the worker thread to finish, if it has not
  164. finished already. When the worker thread is done, the main thread can safely use the results
  165. from the worker thread.
  166. Note that worker threads are useful on all platforms but they do not map to the SPUs on the PS3.
  167. ================================================
  168. */
  169. class idSysThread {
  170. public:
  171. idSysThread();
  172. virtual ~idSysThread();
  173. const char * GetName() const { return name.c_str(); }
  174. uintptr_t GetThreadHandle() const { return threadHandle; }
  175. bool IsRunning() const { return isRunning; }
  176. bool IsTerminating() const { return isTerminating; }
  177. //------------------------
  178. // Thread Start/Stop/Wait
  179. //------------------------
  180. bool StartThread( const char * name, core_t core,
  181. xthreadPriority priority = THREAD_NORMAL,
  182. int stackSize = DEFAULT_THREAD_STACK_SIZE );
  183. bool StartWorkerThread( const char * name, core_t core,
  184. xthreadPriority priority = THREAD_NORMAL,
  185. int stackSize = DEFAULT_THREAD_STACK_SIZE );
  186. void StopThread( bool wait = true );
  187. // This can be called from multiple other threads. However, in the case
  188. // of a worker thread, the work being "done" has little meaning if other
  189. // threads are continuously signalling more work.
  190. void WaitForThread();
  191. //------------------------
  192. // Worker Thread
  193. //------------------------
  194. // Signals the thread to notify work is available.
  195. // This can be called from multiple other threads.
  196. void SignalWork();
  197. // Returns true if the work is done without waiting.
  198. // This can be called from multiple other threads. However, the work
  199. // being "done" has little meaning if other threads are continuously
  200. // signalling more work.
  201. bool IsWorkDone();
  202. protected:
  203. // The routine that performs the work.
  204. virtual int Run();
  205. private:
  206. idStr name;
  207. uintptr_t threadHandle;
  208. bool isWorker;
  209. bool isRunning;
  210. volatile bool isTerminating;
  211. volatile bool moreWorkToDo;
  212. idSysSignal signalWorkerDone;
  213. idSysSignal signalMoreWorkToDo;
  214. idSysMutex signalMutex;
  215. static int ThreadProc( idSysThread * thread );
  216. idSysThread( const idSysThread & s ) {}
  217. void operator=( const idSysThread & s ) {}
  218. };
  219. /*
  220. ================================================
  221. idSysWorkerThreadGroup implements a group of worker threads that
  222. typically crunch through a collection of similar tasks.
  223. class idMyWorkerThread : public idSysThread {
  224. public:
  225. virtual int Run() {
  226. // run thread code here
  227. return 0;
  228. }
  229. // specify thread data here
  230. };
  231. idSysWorkerThreadGroup<idMyWorkerThread> workers( "myWorkers", 4 );
  232. for ( ; ; ) {
  233. for ( int i = 0; i < workers.GetNumThreads(); i++ ) {
  234. // workers.GetThread( i )-> // setup work for this thread
  235. }
  236. workers.SignalWorkAndWait();
  237. // use results from the worker threads here
  238. }
  239. The concept of worker thread Groups is probably most useful for tools and compilers.
  240. For instance, the AAS Compiler is using a worker thread group. Although worker threads
  241. will work well on the PC, Mac and the 360, they do not directly map to the PS3,
  242. in that the worker threads won't automatically run on the SPUs.
  243. ================================================
  244. */
  245. template<class threadType>
  246. class idSysWorkerThreadGroup {
  247. public:
  248. idSysWorkerThreadGroup( const char * name, int numThreads,
  249. xthreadPriority priority = THREAD_NORMAL,
  250. int stackSize = DEFAULT_THREAD_STACK_SIZE );
  251. virtual ~idSysWorkerThreadGroup();
  252. int GetNumThreads() const { return threadList.Num(); }
  253. threadType & GetThread( int i ) { return *threadList[i]; }
  254. void SignalWorkAndWait();
  255. private:
  256. idList<threadType *, TAG_THREAD> threadList;
  257. bool runOneThreadInline; // use the signalling thread as one of the threads
  258. bool singleThreaded; // set to true for debugging
  259. };
  260. /*
  261. ========================
  262. idSysWorkerThreadGroup<threadType>::idSysWorkerThreadGroup
  263. ========================
  264. */
  265. template<class threadType>
  266. ID_INLINE idSysWorkerThreadGroup<threadType>::idSysWorkerThreadGroup( const char * name,
  267. int numThreads, xthreadPriority priority, int stackSize ) {
  268. runOneThreadInline = ( numThreads < 0 );
  269. singleThreaded = false;
  270. numThreads = abs( numThreads );
  271. for( int i = 0; i < numThreads; i++ ) {
  272. threadType *thread = new (TAG_THREAD) threadType;
  273. thread->StartWorkerThread( va( "%s_worker%i", name, i ), (core_t) i, priority, stackSize );
  274. threadList.Append( thread );
  275. }
  276. }
  277. /*
  278. ========================
  279. idSysWorkerThreadGroup<threadType>::~idSysWorkerThreadGroup
  280. ========================
  281. */
  282. template<class threadType>
  283. ID_INLINE idSysWorkerThreadGroup<threadType>::~idSysWorkerThreadGroup() {
  284. threadList.DeleteContents();
  285. }
  286. /*
  287. ========================
  288. idSysWorkerThreadGroup<threadType>::SignalWorkAndWait
  289. ========================
  290. */
  291. template<class threadType>
  292. ID_INLINE void idSysWorkerThreadGroup<threadType>::SignalWorkAndWait() {
  293. if ( singleThreaded ) {
  294. for( int i = 0; i < threadList.Num(); i++ ) {
  295. threadList[ i ]->Run();
  296. }
  297. return;
  298. }
  299. for( int i = 0; i < threadList.Num() - runOneThreadInline; i++ ) {
  300. threadList[ i ]->SignalWork();
  301. }
  302. if ( runOneThreadInline ) {
  303. threadList[ threadList.Num() - 1 ]->Run();
  304. }
  305. for ( int i = 0; i < threadList.Num() - runOneThreadInline; i++ ) {
  306. threadList[ i ]->WaitForThread();
  307. }
  308. }
  309. /*
  310. ================================================
  311. idSysThreadSynchronizer, allows a group of threads to
  312. synchronize with each other half-way through execution.
  313. idSysThreadSynchronizer sync;
  314. class idMyWorkerThread : public idSysThread {
  315. public:
  316. virtual int Run() {
  317. // perform first part of the work here
  318. sync.Synchronize( threadNum ); // synchronize all threads
  319. // perform second part of the work here
  320. return 0;
  321. }
  322. // specify thread data here
  323. unsigned int threadNum;
  324. };
  325. idSysWorkerThreadGroup<idMyWorkerThread> workers( "myWorkers", 4 );
  326. for ( int i = 0; i < workers.GetNumThreads(); i++ ) {
  327. workers.GetThread( i )->threadNum = i;
  328. }
  329. for ( ; ; ) {
  330. for ( int i = 0; i < workers.GetNumThreads(); i++ ) {
  331. // workers.GetThread( i )-> // setup work for this thread
  332. }
  333. workers.SignalWorkAndWait();
  334. // use results from the worker threads here
  335. }
  336. ================================================
  337. */
  338. class idSysThreadSynchronizer {
  339. public:
  340. static const int WAIT_INFINITE = -1;
  341. ID_INLINE void SetNumThreads( unsigned int num );
  342. ID_INLINE void Signal( unsigned int threadNum );
  343. ID_INLINE bool Synchronize( unsigned int threadNum, int timeout = WAIT_INFINITE );
  344. private:
  345. idList< idSysSignal *, TAG_THREAD > signals;
  346. idSysInterlockedInteger busyCount;
  347. };
  348. /*
  349. ========================
  350. idSysThreadSynchronizer::SetNumThreads
  351. ========================
  352. */
  353. ID_INLINE void idSysThreadSynchronizer::SetNumThreads( unsigned int num ) {
  354. assert( busyCount.GetValue() == signals.Num() );
  355. if ( (int)num != signals.Num() ) {
  356. signals.DeleteContents();
  357. signals.SetNum( (int)num );
  358. for ( unsigned int i = 0; i < num; i++ ) {
  359. signals[i] = new (TAG_THREAD) idSysSignal();
  360. }
  361. busyCount.SetValue( num );
  362. SYS_MEMORYBARRIER;
  363. }
  364. }
  365. /*
  366. ========================
  367. idSysThreadSynchronizer::Signal
  368. ========================
  369. */
  370. ID_INLINE void idSysThreadSynchronizer::Signal( unsigned int threadNum ) {
  371. if ( busyCount.Decrement() == 0 ) {
  372. busyCount.SetValue( (unsigned int) signals.Num() );
  373. SYS_MEMORYBARRIER;
  374. for ( int i = 0; i < signals.Num(); i++ ) {
  375. signals[i]->Raise();
  376. }
  377. }
  378. }
  379. /*
  380. ========================
  381. idSysThreadSynchronizer::Synchronize
  382. ========================
  383. */
  384. ID_INLINE bool idSysThreadSynchronizer::Synchronize( unsigned int threadNum, int timeout ) {
  385. return signals[threadNum]->Wait( timeout );
  386. }
  387. #endif // !__THREAD_H__