BsThreadPool.h 7.0 KB

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