thread.h 6.1 KB

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