BsThreadPool.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #pragma once
  2. #include "BsPrerequisitesUtil.h"
  3. #include "BsModule.h"
  4. namespace BansheeEngine
  5. {
  6. class ThreadPool;
  7. /**
  8. * @brief Handle to a thread managed by ThreadPool.
  9. */
  10. class BS_UTILITY_EXPORT HThread
  11. {
  12. public:
  13. HThread();
  14. HThread(ThreadPool* pool, UINT32 threadId);
  15. /**
  16. * @brief Block the calling thread until the thread this handle points to completes.
  17. */
  18. void blockUntilComplete();
  19. private:
  20. UINT32 mThreadId;
  21. ThreadPool* mPool;
  22. };
  23. /**
  24. * @brief Wrapper around a thread that is used within ThreadPool.
  25. */
  26. class BS_UTILITY_EXPORT PooledThread
  27. {
  28. public:
  29. PooledThread(const String& name);
  30. virtual ~PooledThread();
  31. /**
  32. * @brief Initializes the pooled thread. Must be called
  33. * right after the object is constructed.
  34. */
  35. void initialize();
  36. /**
  37. * @brief Starts executing the given worker method.
  38. *
  39. * @note Caller must ensure worker method is not null and that the thread
  40. * is currently idle, otherwise undefined behavior will occur.
  41. */
  42. void start(std::function<void()> workerMethod, UINT32 id);
  43. /**
  44. * @brief Attempts to join the currently running thread and destroys it. Caller must ensure
  45. * that any worker method currently running properly returns, otherwise this
  46. * will block indefinitely.
  47. */
  48. void destroy();
  49. /**
  50. * @brief Returns true if the thread is idle and new worker method can be scheduled on it.
  51. */
  52. bool isIdle();
  53. /**
  54. * @brief Returns how long has the thread been idle. Value is undefined if thread is not idle.
  55. */
  56. time_t idleTime();
  57. /**
  58. * @brief Sets a name of the thread.
  59. */
  60. void setName(const String& name);
  61. /**
  62. * @brief Gets unique ID of the currently executing thread.
  63. */
  64. UINT32 getId() const;
  65. /**
  66. * @brief Called when the thread is first created.
  67. */
  68. virtual void onThreadStarted(const String& name) = 0;
  69. /**
  70. * @brief Called when the thread is being shut down.
  71. */
  72. virtual void onThreadEnded(const String& name) = 0;
  73. protected:
  74. friend class HThread;
  75. /**
  76. * @brief Primary worker method that is ran when the thread is first
  77. * initialized.
  78. */
  79. void run();
  80. protected:
  81. std::function<void()> mWorkerMethod;
  82. String mName;
  83. UINT32 mId;
  84. bool mIdle;
  85. bool mThreadStarted;
  86. bool mThreadReady;
  87. time_t mIdleTime;
  88. BS_THREAD_TYPE* mThread;
  89. BS_MUTEX(mMutex);
  90. BS_THREAD_SYNCHRONISER(mStartedCond);
  91. BS_THREAD_SYNCHRONISER(mReadyCond);
  92. BS_THREAD_SYNCHRONISER(mWorkerEndedCond);
  93. };
  94. /**
  95. * @copydoc PooledThread
  96. *
  97. * @tparam ThreadPolicy Allows you specify a policy with methods that will get called
  98. * whenever a new thread is created or when a thread is destroyed.
  99. */
  100. template<class ThreadPolicy>
  101. class TPooledThread : public PooledThread
  102. {
  103. public:
  104. TPooledThread(const String& name)
  105. :PooledThread(name)
  106. { }
  107. /**
  108. * @copydoc PooledThread::onThreadStarted
  109. */
  110. void onThreadStarted(const String& name)
  111. {
  112. ThreadPolicy::onThreadStarted(name);
  113. }
  114. /**
  115. * @copydoc PooledThread::onThreadEnded
  116. */
  117. void onThreadEnded(const String& name)
  118. {
  119. ThreadPolicy::onThreadEnded(name);
  120. }
  121. };
  122. /**
  123. * @brief Class that maintains a pool of threads we can easily retrieve and use
  124. * for any task. This saves on the cost of creating and destroying threads.
  125. */
  126. class BS_UTILITY_EXPORT ThreadPool : public Module<ThreadPool>
  127. {
  128. public:
  129. /**
  130. * @brief Constructs a new thread pool
  131. *
  132. * @param threadCapacity Default thread capacity, the pool will always
  133. * try to keep this many threads available.
  134. * @param maxCapacity (optional) Maximum number of threads the pool can create.
  135. * If we go over this limit an exception will be thrown.
  136. * @param idleTimeout (optional) How many seconds do threads need to be idle before
  137. * we remove them from the pool
  138. */
  139. ThreadPool(UINT32 threadCapacity, UINT32 maxCapacity = 16, UINT32 idleTimeout = 60);
  140. virtual ~ThreadPool();
  141. /**
  142. * @brief Find an unused thread (or creates a new one) and runs the specified worker
  143. * method on it.
  144. *
  145. * @param name A name you may use for more easily identifying the thread.
  146. * @param workerMethod The worker method to be called by the thread.
  147. *
  148. * @returns A thread handle you may use for monitoring the thread execution.
  149. */
  150. HThread run(const String& name, std::function<void()> workerMethod);
  151. /**
  152. * @brief Stops all threads and destroys them. Caller must ensure each threads workerMethod
  153. * returns otherwise this will never return.
  154. */
  155. void stopAll();
  156. /**
  157. * @brief Clear any unused threads that are over the capacity.
  158. */
  159. void clearUnused();
  160. /**
  161. * @brief Returns the number of unused threads in the pool.
  162. */
  163. UINT32 getNumAvailable() const;
  164. /**
  165. * @brief Returns the number of running threads in the pool.
  166. */
  167. UINT32 getNumActive() const;
  168. /**
  169. * @brief Returns the total number of created threads in the pool
  170. * (both running and unused).
  171. */
  172. UINT32 getNumAllocated() const;
  173. protected:
  174. friend class HThread;
  175. Vector<PooledThread*> mThreads;
  176. /**
  177. * @brief Creates a new thread to be used by the pool.
  178. */
  179. virtual PooledThread* createThread(const String& name) = 0;
  180. /**
  181. * @brief Destroys the specified thread. Caller needs to make sure
  182. * the thread is actually shut down beforehand.
  183. */
  184. void destroyThread(PooledThread* thread);
  185. /**
  186. * @brief Returns the first unused thread if one exists, otherwise
  187. * creates a new one.
  188. *
  189. * @param name Name to assign the thread.
  190. *
  191. * @note Throws an exception if we have reached our maximum thread capacity.
  192. */
  193. PooledThread* getThread(const String& name);
  194. UINT32 mDefaultCapacity;
  195. UINT32 mMaxCapacity;
  196. UINT32 mIdleTimeout;
  197. UINT32 mAge;
  198. std::atomic_uint mUniqueId;
  199. BS_MUTEX(mMutex);
  200. };
  201. /**
  202. * @brief Policy used for thread start & end used by the ThreadPool.
  203. */
  204. class ThreadNoPolicy
  205. {
  206. public:
  207. static void onThreadStarted(const String& name) { }
  208. static void onThreadEnded(const String& name) { }
  209. };
  210. /**
  211. * @copydoc ThreadPool
  212. *
  213. * @tparam ThreadPolicy Allows you specify a policy with methods that will get called
  214. * whenever a new thread is created or when a thread is destroyed.
  215. */
  216. template<class ThreadPolicy = ThreadNoPolicy>
  217. class TThreadPool : public ThreadPool
  218. {
  219. public:
  220. TThreadPool(UINT32 threadCapacity, UINT32 maxCapacity = 16, UINT32 idleTimeout = 60)
  221. :ThreadPool(threadCapacity, maxCapacity, idleTimeout)
  222. {
  223. }
  224. protected:
  225. /**
  226. * @copydoc ThreadPool::createThread
  227. */
  228. PooledThread* createThread(const String& name)
  229. {
  230. PooledThread* newThread = bs_new<TPooledThread<ThreadPolicy>>(name);
  231. newThread->initialize();
  232. return newThread;
  233. }
  234. };
  235. }