BsThreadPool.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsThreadPool.h"
  4. #if BS_PLATFORM == BS_PLATFORM_WIN32
  5. #include "windows.h"
  6. #if BS_COMPILER == BS_COMPILER_MSVC
  7. // disable: nonstandard extension used: 'X' uses SEH and 'Y' has destructor
  8. // We don't care about this as any exception is meant to crash the program.
  9. #pragma warning(disable: 4509)
  10. #endif // BS_COMPILER == BS_COMPILER_MSVC
  11. #endif // BS_PLATFORM == BS_PLATFORM_WIN32
  12. namespace BansheeEngine
  13. {
  14. HThread::HThread()
  15. :mThreadId(0), mPool(nullptr)
  16. { }
  17. HThread::HThread(ThreadPool* pool, UINT32 threadId)
  18. :mThreadId(threadId), mPool(pool)
  19. { }
  20. void HThread::blockUntilComplete()
  21. {
  22. PooledThread* parentThread = nullptr;
  23. {
  24. Lock lock(mPool->mMutex);
  25. for (auto& thread : mPool->mThreads)
  26. {
  27. if (thread->getId() == mThreadId)
  28. {
  29. parentThread = thread;
  30. break;
  31. }
  32. }
  33. }
  34. if (parentThread != nullptr)
  35. {
  36. Lock lock(parentThread->mMutex);
  37. if (parentThread->mId == mThreadId) // Check again in case it changed
  38. {
  39. while (!parentThread->mIdle)
  40. parentThread->mWorkerEndedCond.wait(lock);
  41. }
  42. }
  43. }
  44. PooledThread::PooledThread(const String& name)
  45. :mName(name), mId(0), mIdle(true), mThreadStarted(false),
  46. mThreadReady(false), mIdleTime(0)
  47. { }
  48. PooledThread::~PooledThread()
  49. { }
  50. void PooledThread::initialize()
  51. {
  52. mThread = bs_new<Thread>(std::bind(&PooledThread::run, this));
  53. Lock lock(mMutex);
  54. while(!mThreadStarted)
  55. mStartedCond.wait(lock);
  56. }
  57. void PooledThread::start(std::function<void()> workerMethod, UINT32 id)
  58. {
  59. {
  60. Lock lock(mMutex);
  61. mWorkerMethod = workerMethod;
  62. mIdle = false;
  63. mIdleTime = std::time(nullptr);
  64. mThreadReady = true;
  65. mId = id;
  66. }
  67. mReadyCond.notify_one();
  68. }
  69. void PooledThread::run()
  70. {
  71. onThreadStarted(mName);
  72. {
  73. Lock lock(mMutex);
  74. mThreadStarted = true;
  75. }
  76. mStartedCond.notify_one();
  77. while(true)
  78. {
  79. std::function<void()> worker = nullptr;
  80. {
  81. {
  82. Lock lock(mMutex);
  83. while (!mThreadReady)
  84. mReadyCond.wait(lock);
  85. worker = mWorkerMethod;
  86. }
  87. if (worker == nullptr)
  88. {
  89. onThreadEnded(mName);
  90. return;
  91. }
  92. }
  93. #if BS_PLATFORM == BS_PLATFORM_WIN32
  94. __try
  95. {
  96. worker();
  97. }
  98. __except (gCrashHandler().reportCrash(GetExceptionInformation()))
  99. {
  100. PlatformUtility::terminate(true);
  101. }
  102. #else
  103. worker();
  104. LOGWRN("Starting a thread with no error handling.");
  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. mThreads.push_back(thread);
  208. else
  209. destroyThread(thread);
  210. }
  211. mThreads.insert(mThreads.end(), activeThreads.begin(), activeThreads.end());
  212. }
  213. void ThreadPool::destroyThread(PooledThread* thread)
  214. {
  215. thread->destroy();
  216. bs_delete(thread);
  217. }
  218. PooledThread* ThreadPool::getThread(const String& name)
  219. {
  220. UINT32 age = 0;
  221. {
  222. Lock lock(mMutex);
  223. age = ++mAge;
  224. }
  225. if(age == 32)
  226. clearUnused();
  227. PooledThread* newThread = nullptr;
  228. Lock lock(mMutex);
  229. for(auto& thread : mThreads)
  230. {
  231. if(thread->isIdle())
  232. {
  233. thread->setName(name);
  234. return thread;
  235. }
  236. }
  237. if(newThread == nullptr)
  238. {
  239. if(mThreads.size() >= mMaxCapacity)
  240. BS_EXCEPT(InvalidStateException, "Unable to create a new thread in the pool because maximum capacity has been reached.");
  241. newThread = createThread(name);
  242. mThreads.push_back(newThread);
  243. }
  244. return newThread;
  245. }
  246. UINT32 ThreadPool::getNumAvailable() const
  247. {
  248. UINT32 numAvailable = 0;
  249. Lock lock(mMutex);
  250. for(auto& thread : mThreads)
  251. {
  252. if(thread->isIdle())
  253. numAvailable++;
  254. }
  255. return numAvailable;
  256. }
  257. UINT32 ThreadPool::getNumActive() const
  258. {
  259. UINT32 numActive = 0;
  260. Lock lock(mMutex);
  261. for(auto& thread : mThreads)
  262. {
  263. if(!thread->isIdle())
  264. numActive++;
  265. }
  266. return numActive;
  267. }
  268. UINT32 ThreadPool::getNumAllocated() const
  269. {
  270. Lock lock(mMutex);
  271. return (UINT32)mThreads.size();
  272. }
  273. }