2
0

BsThreadPool.cpp 6.3 KB

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