BsThreadPool.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #include "BsThreadPool.h"
  2. #if BS_PLATFORM == BS_PLATFORM_WIN32
  3. #include "windows.h"
  4. #if BS_COMPILER == BS_COMPILER_MSVC
  5. // disable: nonstandard extension used: 'X' uses SEH and 'Y' has destructor
  6. // We don't care about this as any exception is meant to crash the program.
  7. #pragma warning(disable: 4509)
  8. #endif // BS_COMPILER == BS_COMPILER_MSVC
  9. #endif // BS_PLATFORM == BS_PLATFORM_WIN32
  10. namespace BansheeEngine
  11. {
  12. HThread::HThread()
  13. :mPool(nullptr), mThreadId(0)
  14. { }
  15. HThread::HThread(ThreadPool* pool, UINT32 threadId)
  16. :mPool(pool), mThreadId(threadId)
  17. { }
  18. void HThread::blockUntilComplete()
  19. {
  20. PooledThread* parentThread = nullptr;
  21. {
  22. BS_LOCK_MUTEX(mPool->mMutex);
  23. for (auto& thread : mPool->mThreads)
  24. {
  25. if (thread->getId() == mThreadId)
  26. {
  27. parentThread = thread;
  28. break;
  29. }
  30. }
  31. }
  32. if (parentThread != nullptr)
  33. {
  34. BS_LOCK_MUTEX_NAMED(parentThread->mMutex, lock);
  35. if (parentThread->mId == mThreadId) // Check again in case it changed
  36. {
  37. while (!parentThread->mIdle)
  38. BS_THREAD_WAIT(parentThread->mWorkerEndedCond, parentThread->mMutex, lock);
  39. }
  40. }
  41. }
  42. PooledThread::PooledThread(const String& name)
  43. :mName(name), mIdle(true), mThreadStarted(false),
  44. mThreadReady(false), mIdleTime(0), mId(0)
  45. { }
  46. PooledThread::~PooledThread()
  47. { }
  48. void PooledThread::initialize()
  49. {
  50. BS_THREAD_CREATE(t, std::bind(&PooledThread::run, this));
  51. mThread = t;
  52. BS_LOCK_MUTEX_NAMED(mMutex, lock);
  53. while(!mThreadStarted)
  54. BS_THREAD_WAIT(mStartedCond, mMutex, lock);
  55. }
  56. void PooledThread::start(std::function<void()> workerMethod, UINT32 id)
  57. {
  58. {
  59. BS_LOCK_MUTEX(mMutex);
  60. mWorkerMethod = workerMethod;
  61. mIdle = false;
  62. mIdleTime = std::time(nullptr);
  63. mThreadReady = true;
  64. mId = id;
  65. }
  66. BS_THREAD_NOTIFY_ONE(mReadyCond);
  67. }
  68. void PooledThread::run()
  69. {
  70. onThreadStarted(mName);
  71. {
  72. BS_LOCK_MUTEX(mMutex);
  73. mThreadStarted = true;
  74. }
  75. BS_THREAD_NOTIFY_ONE(mStartedCond);
  76. while(true)
  77. {
  78. std::function<void()> worker = nullptr;
  79. {
  80. {
  81. BS_LOCK_MUTEX_NAMED(mMutex, lock);
  82. while (!mThreadReady)
  83. BS_THREAD_WAIT(mReadyCond, mMutex, lock);
  84. worker = mWorkerMethod;
  85. }
  86. if (worker == nullptr)
  87. {
  88. onThreadEnded(mName);
  89. return;
  90. }
  91. }
  92. #if BS_PLATFORM == BS_PLATFORM_WIN32
  93. __try
  94. {
  95. worker();
  96. }
  97. __except (gCrashHandler().reportCrash(GetExceptionInformation()))
  98. {
  99. PlatformUtility::terminate(true);
  100. }
  101. #else
  102. worker();
  103. LOGWRN("Starting a thread with no error handling.");
  104. #endif
  105. {
  106. BS_LOCK_MUTEX(mMutex);
  107. mIdle = true;
  108. mIdleTime = std::time(nullptr);
  109. mThreadReady = false;
  110. mWorkerMethod = nullptr; // Make sure to clear as it could have bound shared pointers and similar
  111. BS_THREAD_NOTIFY_ONE(mWorkerEndedCond);
  112. }
  113. }
  114. }
  115. void PooledThread::destroy()
  116. {
  117. blockUntilComplete();
  118. {
  119. BS_LOCK_MUTEX(mMutex);
  120. mWorkerMethod = nullptr;
  121. mThreadReady = true;
  122. }
  123. BS_THREAD_NOTIFY_ONE(mReadyCond);
  124. BS_THREAD_JOIN((*mThread));
  125. BS_THREAD_DESTROY(mThread);
  126. }
  127. void PooledThread::blockUntilComplete()
  128. {
  129. BS_LOCK_MUTEX_NAMED(mMutex, lock);
  130. while (!mIdle)
  131. BS_THREAD_WAIT(mWorkerEndedCond, mMutex, lock);
  132. }
  133. bool PooledThread::isIdle()
  134. {
  135. BS_LOCK_MUTEX(mMutex);
  136. return mIdle;
  137. }
  138. time_t PooledThread::idleTime()
  139. {
  140. BS_LOCK_MUTEX(mMutex);
  141. return (time(nullptr) - mIdleTime);
  142. }
  143. void PooledThread::setName(const String& name)
  144. {
  145. mName = name;
  146. }
  147. UINT32 PooledThread::getId() const
  148. {
  149. BS_LOCK_MUTEX(mMutex);
  150. return mId;
  151. }
  152. ThreadPool::ThreadPool(UINT32 threadCapacity, UINT32 maxCapacity, UINT32 idleTimeout)
  153. :mDefaultCapacity(threadCapacity), mMaxCapacity(maxCapacity), mIdleTimeout(idleTimeout), mAge(0)
  154. {
  155. }
  156. ThreadPool::~ThreadPool()
  157. {
  158. stopAll();
  159. }
  160. HThread ThreadPool::run(const String& name, std::function<void()> workerMethod)
  161. {
  162. PooledThread* thread = getThread(name);
  163. thread->start(workerMethod, mUniqueId++);
  164. return HThread(this, thread->getId());
  165. }
  166. void ThreadPool::stopAll()
  167. {
  168. BS_LOCK_MUTEX(mMutex);
  169. for(auto& thread : mThreads)
  170. {
  171. destroyThread(thread);
  172. }
  173. mThreads.clear();
  174. }
  175. void ThreadPool::clearUnused()
  176. {
  177. BS_LOCK_MUTEX(mMutex);
  178. mAge = 0;
  179. if(mThreads.size() <= mDefaultCapacity)
  180. return;
  181. Vector<PooledThread*> idleThreads;
  182. Vector<PooledThread*> expiredThreads;
  183. Vector<PooledThread*> activeThreads;
  184. idleThreads.reserve(mThreads.size());
  185. expiredThreads.reserve(mThreads.size());
  186. activeThreads.reserve(mThreads.size());
  187. for(auto& thread : mThreads)
  188. {
  189. if(thread->isIdle())
  190. {
  191. if(thread->idleTime() >= mIdleTimeout)
  192. expiredThreads.push_back(thread);
  193. else
  194. idleThreads.push_back(thread);
  195. }
  196. else
  197. activeThreads.push_back(thread);
  198. }
  199. idleThreads.insert(idleThreads.end(), expiredThreads.begin(), expiredThreads.end());
  200. UINT32 limit = std::min((UINT32)idleThreads.size(), mDefaultCapacity);
  201. UINT32 i = 0;
  202. mThreads.clear();
  203. for(auto& thread : idleThreads)
  204. {
  205. if(i < limit)
  206. mThreads.push_back(thread);
  207. else
  208. destroyThread(thread);
  209. }
  210. mThreads.insert(mThreads.end(), activeThreads.begin(), activeThreads.end());
  211. }
  212. void ThreadPool::destroyThread(PooledThread* thread)
  213. {
  214. thread->destroy();
  215. bs_delete(thread);
  216. }
  217. PooledThread* ThreadPool::getThread(const String& name)
  218. {
  219. UINT32 age = 0;
  220. {
  221. BS_LOCK_MUTEX(mMutex);
  222. age = ++mAge;
  223. }
  224. if(age == 32)
  225. clearUnused();
  226. PooledThread* newThread = nullptr;
  227. BS_LOCK_MUTEX(mMutex);
  228. for(auto& thread : mThreads)
  229. {
  230. if(thread->isIdle())
  231. {
  232. thread->setName(name);
  233. return thread;
  234. }
  235. }
  236. if(newThread == nullptr)
  237. {
  238. if(mThreads.size() >= mMaxCapacity)
  239. BS_EXCEPT(InvalidStateException, "Unable to create a new thread in the pool because maximum capacity has been reached.");
  240. newThread = createThread(name);
  241. mThreads.push_back(newThread);
  242. }
  243. return newThread;
  244. }
  245. UINT32 ThreadPool::getNumAvailable() const
  246. {
  247. UINT32 numAvailable = 0;
  248. BS_LOCK_MUTEX(mMutex);
  249. for(auto& thread : mThreads)
  250. {
  251. if(thread->isIdle())
  252. numAvailable++;
  253. }
  254. return numAvailable;
  255. }
  256. UINT32 ThreadPool::getNumActive() const
  257. {
  258. UINT32 numActive = 0;
  259. BS_LOCK_MUTEX(mMutex);
  260. for(auto& thread : mThreads)
  261. {
  262. if(!thread->isIdle())
  263. numActive++;
  264. }
  265. return numActive;
  266. }
  267. UINT32 ThreadPool::getNumAllocated() const
  268. {
  269. BS_LOCK_MUTEX(mMutex);
  270. return (UINT32)mThreads.size();
  271. }
  272. }