BsThreadPool.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 Blocks the current thread until this thread completes.
  67. * Returns immediately if the thread is idle.
  68. */
  69. void blockUntilComplete();
  70. /**
  71. * @brief Called when the thread is first created.
  72. */
  73. virtual void onThreadStarted(const String& name) = 0;
  74. /**
  75. * @brief Called when the thread is being shut down.
  76. */
  77. virtual void onThreadEnded(const String& name) = 0;
  78. protected:
  79. friend class HThread;
  80. /**
  81. * @brief Primary worker method that is ran when the thread is first
  82. * initialized.
  83. */
  84. void run();
  85. protected:
  86. std::function<void()> mWorkerMethod;
  87. String mName;
  88. UINT32 mId;
  89. bool mIdle;
  90. bool mThreadStarted;
  91. bool mThreadReady;
  92. time_t mIdleTime;
  93. BS_THREAD_TYPE* mThread;
  94. BS_MUTEX(mMutex);
  95. BS_THREAD_SYNCHRONISER(mStartedCond);
  96. BS_THREAD_SYNCHRONISER(mReadyCond);
  97. BS_THREAD_SYNCHRONISER(mWorkerEndedCond);
  98. };
  99. /**
  100. * @copydoc PooledThread
  101. *
  102. * @tparam ThreadPolicy Allows you specify a policy with methods that will get called
  103. * whenever a new thread is created or when a thread is destroyed.
  104. */
  105. template<class ThreadPolicy>
  106. class TPooledThread : public PooledThread
  107. {
  108. public:
  109. TPooledThread(const String& name)
  110. :PooledThread(name)
  111. { }
  112. /**
  113. * @copydoc PooledThread::onThreadStarted
  114. */
  115. void onThreadStarted(const String& name)
  116. {
  117. ThreadPolicy::onThreadStarted(name);
  118. }
  119. /**
  120. * @copydoc PooledThread::onThreadEnded
  121. */
  122. void onThreadEnded(const String& name)
  123. {
  124. ThreadPolicy::onThreadEnded(name);
  125. }
  126. };
  127. /**
  128. * @brief Class that maintains a pool of threads we can easily retrieve and use
  129. * for any task. This saves on the cost of creating and destroying threads.
  130. */
  131. class BS_UTILITY_EXPORT ThreadPool : public Module<ThreadPool>
  132. {
  133. public:
  134. /**
  135. * @brief Constructs a new thread pool
  136. *
  137. * @param threadCapacity Default thread capacity, the pool will always
  138. * try to keep this many threads available.
  139. * @param maxCapacity (optional) Maximum number of threads the pool can create.
  140. * If we go over this limit an exception will be thrown.
  141. * @param idleTimeout (optional) How many seconds do threads need to be idle before
  142. * we remove them from the pool
  143. */
  144. ThreadPool(UINT32 threadCapacity, UINT32 maxCapacity = 16, UINT32 idleTimeout = 60);
  145. virtual ~ThreadPool();
  146. /**
  147. * @brief Find an unused thread (or creates a new one) and runs the specified worker
  148. * method on it.
  149. *
  150. * @param name A name you may use for more easily identifying the thread.
  151. * @param workerMethod The worker method to be called by the thread.
  152. *
  153. * @returns A thread handle you may use for monitoring the thread execution.
  154. */
  155. HThread run(const String& name, std::function<void()> workerMethod);
  156. /**
  157. * @brief Stops all threads and destroys them. Caller must ensure each threads workerMethod
  158. * returns otherwise this will never return.
  159. */
  160. void stopAll();
  161. /**
  162. * @brief Clear any unused threads that are over the capacity.
  163. */
  164. void clearUnused();
  165. /**
  166. * @brief Returns the number of unused threads in the pool.
  167. */
  168. UINT32 getNumAvailable() const;
  169. /**
  170. * @brief Returns the number of running threads in the pool.
  171. */
  172. UINT32 getNumActive() const;
  173. /**
  174. * @brief Returns the total number of created threads in the pool
  175. * (both running and unused).
  176. */
  177. UINT32 getNumAllocated() const;
  178. protected:
  179. friend class HThread;
  180. Vector<PooledThread*> mThreads;
  181. /**
  182. * @brief Creates a new thread to be used by the pool.
  183. */
  184. virtual PooledThread* createThread(const String& name) = 0;
  185. /**
  186. * @brief Destroys the specified thread. Caller needs to make sure
  187. * the thread is actually shut down beforehand.
  188. */
  189. void destroyThread(PooledThread* thread);
  190. /**
  191. * @brief Returns the first unused thread if one exists, otherwise
  192. * creates a new one.
  193. *
  194. * @param name Name to assign the thread.
  195. *
  196. * @note Throws an exception if we have reached our maximum thread capacity.
  197. */
  198. PooledThread* getThread(const String& name);
  199. UINT32 mDefaultCapacity;
  200. UINT32 mMaxCapacity;
  201. UINT32 mIdleTimeout;
  202. UINT32 mAge;
  203. std::atomic_uint mUniqueId;
  204. BS_MUTEX(mMutex);
  205. };
  206. /**
  207. * @brief Policy used for thread start & end used by the ThreadPool.
  208. */
  209. class ThreadNoPolicy
  210. {
  211. public:
  212. static void onThreadStarted(const String& name) { }
  213. static void onThreadEnded(const String& name) { }
  214. };
  215. /**
  216. * @copydoc ThreadPool
  217. *
  218. * @tparam ThreadPolicy Allows you specify a policy with methods that will get called
  219. * whenever a new thread is created or when a thread is destroyed.
  220. */
  221. template<class ThreadPolicy = ThreadNoPolicy>
  222. class TThreadPool : public ThreadPool
  223. {
  224. public:
  225. TThreadPool(UINT32 threadCapacity, UINT32 maxCapacity = 16, UINT32 idleTimeout = 60)
  226. :ThreadPool(threadCapacity, maxCapacity, idleTimeout)
  227. {
  228. }
  229. protected:
  230. /**
  231. * @copydoc ThreadPool::createThread
  232. */
  233. PooledThread* createThread(const String& name)
  234. {
  235. PooledThread* newThread = bs_new<TPooledThread<ThreadPolicy>>(name);
  236. newThread->initialize();
  237. return newThread;
  238. }
  239. };
  240. }