2
0

thread.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _PLATFORM_THREADS_THREAD_H_
  23. #define _PLATFORM_THREADS_THREAD_H_
  24. #ifndef _TORQUE_TYPES_H_
  25. #include "platform/types.h"
  26. #endif
  27. #ifndef _TVECTOR_H_
  28. #include "core/util/tVector.h"
  29. #endif
  30. #ifndef _PLATFORM_THREADS_MUTEX_H_
  31. #include "platform/threads/mutex.h"
  32. #endif
  33. #ifndef _TSINGLETON_H_
  34. #include "core/util/tSingleton.h"
  35. #endif
  36. // Forward ref used by platform code
  37. class PlatformThreadData;
  38. // Typedefs
  39. typedef void (*ThreadRunFunction)(void *data);
  40. class Thread
  41. {
  42. public:
  43. typedef void Parent;
  44. protected:
  45. PlatformThreadData* mData;
  46. /// Used to signal threads need to stop.
  47. /// Threads set this flag to false in start()
  48. U32 shouldStop;
  49. /// Set the name of this thread for identification in debuggers.
  50. /// Maybe a NOP on platforms that do not support this. Always a NOP
  51. /// in non-debug builds.
  52. void _setName( const char* name );
  53. public:
  54. /// If set, the thread will delete itself once it has finished running.
  55. bool autoDelete;
  56. /// Create a thread.
  57. /// @param func The starting function for the thread.
  58. /// @param arg Data to be passed to func, when the thread starts.
  59. /// @param start_thread Supported for compatibility. Must be false. Starting threads from
  60. /// within the constructor is not allowed anymore as the run() method is virtual.
  61. Thread(ThreadRunFunction func = 0, void *arg = 0, bool start_thread = false, bool autodelete = false);
  62. /// Destroy a thread.
  63. /// The thread MUST be allowed to exit before it is destroyed.
  64. virtual ~Thread();
  65. /// Start a thread.
  66. /// Sets shouldStop to false and calls run() in a new thread of execution.
  67. void start( void* arg = 0 );
  68. /// Ask a thread to stop running.
  69. void stop()
  70. {
  71. shouldStop = true;
  72. }
  73. /// Block until the thread stops running.
  74. /// @note Don't use this in combination with auto-deletion as otherwise the thread will kill
  75. /// itself while still executing the join() method on the waiting thread.
  76. bool join();
  77. /// Threads may call checkForStop() periodically to check if they've been
  78. /// asked to stop. As soon as checkForStop() returns true, the thread should
  79. /// clean up and return.
  80. bool checkForStop()
  81. {
  82. return shouldStop;
  83. }
  84. /// Run the Thread's entry point function.
  85. /// Override this method in a subclass of Thread to create threaded code in
  86. /// an object oriented way, and without passing a function ptr to Thread().
  87. /// Also, you can call this method directly to execute the thread's
  88. /// code in a non-threaded way.
  89. virtual void run(void *arg = 0);
  90. /// Returns true if the thread is running.
  91. bool isAlive();
  92. /// Returns the platform specific thread id for this thread.
  93. dsize_t getId();
  94. };
  95. ///
  96. class ThreadManager
  97. {
  98. Vector<Thread*> threadPool;
  99. Mutex poolLock;
  100. struct MainThreadId
  101. {
  102. dsize_t mId;
  103. MainThreadId()
  104. {
  105. mId = ThreadManager::getCurrentThreadId();
  106. }
  107. dsize_t get()
  108. {
  109. // Okay, this is a bit soso. The main thread ID may get queried during
  110. // global ctor phase before MainThreadId's ctor ran. Since global
  111. // ctors will/should all run on the main thread, we can sort of safely
  112. // assume here that we can just query the current thread's ID.
  113. if( !mId )
  114. mId = ThreadManager::getCurrentThreadId();
  115. return mId;
  116. }
  117. };
  118. static MainThreadId smMainThreadId;
  119. public:
  120. ThreadManager()
  121. {
  122. VECTOR_SET_ASSOCIATION( threadPool );
  123. }
  124. /// Return true if the caller is running on the main thread.
  125. static bool isMainThread();
  126. /// Returns true if threadId is the same as the calling thread's id.
  127. static bool isCurrentThread(dsize_t threadId);
  128. /// Returns true if the 2 thread ids represent the same thread. Some thread
  129. /// APIs return an opaque object as a thread id, so the == operator cannot
  130. /// reliably compare thread ids.
  131. // this comparator is needed by pthreads and ThreadManager.
  132. static bool compare(dsize_t threadId_1, dsize_t threadId_2);
  133. /// Returns the platform specific thread id of the calling thread. Some
  134. /// platforms do not guarantee that this ID stays the same over the life of
  135. /// the thread, so use ThreadManager::compare() to compare thread ids.
  136. static dsize_t getCurrentThreadId();
  137. /// Returns the platform specific thread id ot the main thread.
  138. static dsize_t getMainThreadId() { return smMainThreadId.get(); }
  139. /// Each thread should add itself to the thread pool the first time it runs.
  140. static void addThread(Thread* thread)
  141. {
  142. ThreadManager &manager = *ManagedSingleton< ThreadManager >::instance();
  143. manager.poolLock.lock();
  144. Thread *alreadyAdded = getThreadById(thread->getId());
  145. if(!alreadyAdded)
  146. manager.threadPool.push_back(thread);
  147. manager.poolLock.unlock();
  148. }
  149. static void removeThread(Thread* thread)
  150. {
  151. ThreadManager &manager = *ManagedSingleton< ThreadManager >::instance();
  152. manager.poolLock.lock();
  153. dsize_t threadID = thread->getId();
  154. for(U32 i = 0;i < manager.threadPool.size();++i)
  155. {
  156. if( compare( manager.threadPool[i]->getId(), threadID ) )
  157. {
  158. manager.threadPool.erase(i);
  159. break;
  160. }
  161. }
  162. manager.poolLock.unlock();
  163. }
  164. /// Searches the pool of known threads for a thread whose id is equivalent to
  165. /// the given threadid. Compares thread ids with ThreadManager::compare().
  166. static Thread* getThreadById(dsize_t threadid)
  167. {
  168. AssertFatal(threadid != 0, "ThreadManager::getThreadById() Searching for a bad thread id.");
  169. Thread* ret = NULL;
  170. ThreadManager &manager = *ManagedSingleton< ThreadManager >::instance();
  171. manager.poolLock.lock();
  172. Vector<Thread*> &pool = manager.threadPool;
  173. for( S32 i = pool.size() - 1; i >= 0; i--)
  174. {
  175. Thread* p = pool[i];
  176. if(compare(p->getId(), threadid))
  177. {
  178. ret = p;
  179. break;
  180. }
  181. }
  182. manager.poolLock.unlock();
  183. return ret;
  184. }
  185. static Thread* getCurrentThread()
  186. {
  187. return getThreadById(ThreadManager::getCurrentThreadId());
  188. }
  189. static const char* getSingletonName()
  190. {
  191. return "ThreadManager";
  192. }
  193. };
  194. inline bool ThreadManager::isMainThread()
  195. {
  196. return compare( ThreadManager::getCurrentThreadId(), smMainThreadId.get() );
  197. }
  198. inline bool ThreadManager::isCurrentThread(dsize_t threadId)
  199. {
  200. dsize_t current = getCurrentThreadId();
  201. return compare(current, threadId);
  202. }
  203. #endif // _PLATFORM_THREADS_THREAD_H_