BsThreadPool.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsThreadPool.h"
  4. #include "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. LOGWRN("Starting a thread with no error handling.");
  106. #endif
  107. {
  108. Lock lock(mMutex);
  109. mIdle = true;
  110. mIdleTime = std::time(nullptr);
  111. mThreadReady = false;
  112. mWorkerMethod = nullptr; // Make sure to clear as it could have bound shared pointers and similar
  113. mWorkerEndedCond.notify_one();
  114. }
  115. }
  116. }
  117. void PooledThread::destroy()
  118. {
  119. blockUntilComplete();
  120. {
  121. Lock lock(mMutex);
  122. mWorkerMethod = nullptr;
  123. mThreadReady = true;
  124. }
  125. mReadyCond.notify_one();
  126. mThread->join();
  127. bs_delete(mThread);
  128. }
  129. void PooledThread::blockUntilComplete()
  130. {
  131. Lock lock(mMutex);
  132. while (!mIdle)
  133. mWorkerEndedCond.wait(lock);
  134. }
  135. bool PooledThread::isIdle()
  136. {
  137. Lock lock(mMutex);
  138. return mIdle;
  139. }
  140. time_t PooledThread::idleTime()
  141. {
  142. Lock lock(mMutex);
  143. return (time(nullptr) - mIdleTime);
  144. }
  145. void PooledThread::setName(const String& name)
  146. {
  147. mName = name;
  148. }
  149. UINT32 PooledThread::getId() const
  150. {
  151. Lock lock(mMutex);
  152. return mId;
  153. }
  154. ThreadPool::ThreadPool(UINT32 threadCapacity, UINT32 maxCapacity, UINT32 idleTimeout)
  155. :mDefaultCapacity(threadCapacity), mMaxCapacity(maxCapacity), mIdleTimeout(idleTimeout), mAge(0)
  156. {
  157. }
  158. ThreadPool::~ThreadPool()
  159. {
  160. stopAll();
  161. }
  162. HThread ThreadPool::run(const String& name, std::function<void()> workerMethod)
  163. {
  164. PooledThread* thread = getThread(name);
  165. thread->start(workerMethod, mUniqueId++);
  166. return HThread(this, thread->getId());
  167. }
  168. void ThreadPool::stopAll()
  169. {
  170. Lock lock(mMutex);
  171. for(auto& thread : mThreads)
  172. {
  173. destroyThread(thread);
  174. }
  175. mThreads.clear();
  176. }
  177. void ThreadPool::clearUnused()
  178. {
  179. Lock lock(mMutex);
  180. mAge = 0;
  181. if(mThreads.size() <= mDefaultCapacity)
  182. return;
  183. Vector<PooledThread*> idleThreads;
  184. Vector<PooledThread*> expiredThreads;
  185. Vector<PooledThread*> activeThreads;
  186. idleThreads.reserve(mThreads.size());
  187. expiredThreads.reserve(mThreads.size());
  188. activeThreads.reserve(mThreads.size());
  189. for(auto& thread : mThreads)
  190. {
  191. if(thread->isIdle())
  192. {
  193. if(thread->idleTime() >= mIdleTimeout)
  194. expiredThreads.push_back(thread);
  195. else
  196. idleThreads.push_back(thread);
  197. }
  198. else
  199. activeThreads.push_back(thread);
  200. }
  201. idleThreads.insert(idleThreads.end(), expiredThreads.begin(), expiredThreads.end());
  202. UINT32 limit = std::min((UINT32)idleThreads.size(), mDefaultCapacity);
  203. UINT32 i = 0;
  204. mThreads.clear();
  205. for(auto& thread : idleThreads)
  206. {
  207. if(i < limit)
  208. mThreads.push_back(thread);
  209. else
  210. destroyThread(thread);
  211. }
  212. mThreads.insert(mThreads.end(), activeThreads.begin(), activeThreads.end());
  213. }
  214. void ThreadPool::destroyThread(PooledThread* thread)
  215. {
  216. thread->destroy();
  217. bs_delete(thread);
  218. }
  219. PooledThread* ThreadPool::getThread(const String& name)
  220. {
  221. UINT32 age = 0;
  222. {
  223. Lock lock(mMutex);
  224. age = ++mAge;
  225. }
  226. if(age == 32)
  227. clearUnused();
  228. PooledThread* newThread = nullptr;
  229. Lock lock(mMutex);
  230. for(auto& thread : mThreads)
  231. {
  232. if(thread->isIdle())
  233. {
  234. thread->setName(name);
  235. return thread;
  236. }
  237. }
  238. if(newThread == nullptr)
  239. {
  240. if(mThreads.size() >= mMaxCapacity)
  241. BS_EXCEPT(InvalidStateException, "Unable to create a new thread in the pool because maximum capacity has been reached.");
  242. newThread = createThread(name);
  243. mThreads.push_back(newThread);
  244. }
  245. return newThread;
  246. }
  247. UINT32 ThreadPool::getNumAvailable() const
  248. {
  249. UINT32 numAvailable = 0;
  250. Lock lock(mMutex);
  251. for(auto& thread : mThreads)
  252. {
  253. if(thread->isIdle())
  254. numAvailable++;
  255. }
  256. return numAvailable;
  257. }
  258. UINT32 ThreadPool::getNumActive() const
  259. {
  260. UINT32 numActive = 0;
  261. Lock lock(mMutex);
  262. for(auto& thread : mThreads)
  263. {
  264. if(!thread->isIdle())
  265. numActive++;
  266. }
  267. return numActive;
  268. }
  269. UINT32 ThreadPool::getNumAllocated() const
  270. {
  271. Lock lock(mMutex);
  272. return (UINT32)mThreads.size();
  273. }
  274. }