BsThreadPool.h 5.9 KB

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