thread.h 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 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. #include "platform/types.h"
  23. #include "collection/vector.h"
  24. #include "platform/threads/mutex.h"
  25. #ifndef _PLATFORM_THREADS_THREAD_H_
  26. #define _PLATFORM_THREADS_THREAD_H_
  27. // Forward ref used by platform code
  28. struct PlatformThreadData;
  29. // Typedefs
  30. typedef void (*ThreadRunFunction)(void *data);
  31. #ifdef TORQUE_CPU_X64
  32. typedef U64 ThreadIdent;
  33. #else
  34. typedef U32 ThreadIdent;
  35. #endif
  36. class Thread
  37. {
  38. protected:
  39. PlatformThreadData* mData;
  40. /// Used to signal threads need to stop.
  41. /// Threads set this flag to false in start()
  42. bool shouldStop;
  43. public:
  44. /// If set, the thread will delete itself once it has finished running.
  45. bool autoDelete;
  46. /// Create a thread.
  47. /// @param func The starting function for the thread.
  48. /// @param arg Data to be passed to func, when the thread starts.
  49. /// @param start_thread Whether to start the Thread immediately.
  50. Thread(ThreadRunFunction func = 0, void *arg = 0, bool start_thread = true, bool autodelete = false);
  51. /// Destroy a thread.
  52. /// The thread MUST be allowed to exit before it is destroyed.
  53. virtual ~Thread();
  54. /// Start a thread.
  55. /// Sets shouldStop to false and calls run() in a new thread of execution.
  56. void start();
  57. /// Ask a thread to stop running.
  58. void stop() { shouldStop = true; }
  59. /// Block until the thread stops running.
  60. bool join();
  61. /// Threads may call checkForStop() periodically to check if they've been
  62. /// asked to stop. As soon as checkForStop() returns true, the thread should
  63. /// clean up and return.
  64. bool checkForStop() { return shouldStop; }
  65. /// Run the Thread's entry point function.
  66. /// Override this method in a subclass of Thread to create threaded code in
  67. /// an object oriented way, and without passing a function ptr to Thread().
  68. /// Also, you can call this method directly to execute the thread's
  69. /// code in a non-threaded way.
  70. virtual void run(void *arg = 0);
  71. /// Returns true if the thread is running.
  72. bool isAlive();
  73. /// Returns the platform specific thread id for this thread.
  74. ThreadIdent getId();
  75. };
  76. class ThreadManager
  77. {
  78. static ThreadManager* singleton()
  79. {
  80. static ThreadManager* man = NULL;
  81. if(!man) man = new ThreadManager;
  82. AssertISV(man, "Thread manager doesn't exist.");
  83. return man;
  84. }
  85. Vector<Thread*> threadPool;
  86. Mutex poolLock;
  87. public:
  88. /// Returns true if threadId is the same as the calling thread's id.
  89. static bool isCurrentThread(ThreadIdent threadId);
  90. /// Returns true if the 2 thread ids represent the same thread. Some thread
  91. /// APIs return an opaque object as a thread id, so the == operator cannot
  92. /// reliably compare thread ids.
  93. // this comparator is needed by pthreads and ThreadManager.
  94. static bool compare(ThreadIdent threadId_1, ThreadIdent threadId_2);
  95. /// Returns the platform specific thread id of the calling thread. Some
  96. /// platforms do not guarantee that this ID stays the same over the life of
  97. /// the thread, so use ThreadManager::compare() to compare thread ids.
  98. static ThreadIdent getCurrentThreadId();
  99. /// Each thread should add itself to the thread pool the first time it runs.
  100. static void addThread(Thread* thread)
  101. {
  102. ThreadManager &manager = *singleton();
  103. manager.poolLock.lock();
  104. Thread *alreadyAdded = getThreadById(thread->getId());
  105. if(!alreadyAdded)
  106. manager.threadPool.push_back(thread);
  107. manager.poolLock.unlock();
  108. }
  109. static void removeThread(Thread* thread)
  110. {
  111. ThreadManager &manager = *singleton();
  112. manager.poolLock.lock();
  113. ThreadIdent threadID = thread->getId();
  114. for( U32 i = 0;i < (U32)manager.threadPool.size();++i)
  115. {
  116. if(manager.threadPool[i]->getId() == threadID)
  117. {
  118. manager.threadPool.erase(i);
  119. break;
  120. }
  121. }
  122. manager.poolLock.unlock();
  123. }
  124. /// Searches the pool of known threads for a thread whose id is equivalent to
  125. /// the given threadid. Compares thread ids with ThreadManager::compare().
  126. static Thread* getThreadById(ThreadIdent threadid)
  127. {
  128. AssertFatal(threadid != 0, "ThreadManager::getThreadById() Searching for a bad thread id.");
  129. Thread* ret = NULL;
  130. singleton()->poolLock.lock();
  131. Vector<Thread*> &pool = singleton()->threadPool;
  132. for( S32 i = pool.size() - 1; i >= 0; i--)
  133. {
  134. Thread* p = pool[i];
  135. if(compare(p->getId(), threadid))
  136. {
  137. ret = p;
  138. break;
  139. }
  140. }
  141. singleton()->poolLock.unlock();
  142. return ret;
  143. }
  144. static Thread* getCurrentThread()
  145. {
  146. return getThreadById(ThreadManager::getCurrentThreadId());
  147. }
  148. };
  149. inline bool ThreadManager::isCurrentThread(ThreadIdent threadId)
  150. {
  151. ThreadIdent current = getCurrentThreadId();
  152. return compare(current, threadId);
  153. }
  154. #endif // _PLATFORM_THREADS_THREAD_H_