BsThreadPool.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. :mPool(nullptr), mThreadId(0)
  16. { }
  17. HThread::HThread(ThreadPool* pool, UINT32 threadId)
  18. :mPool(pool), mThreadId(threadId)
  19. { }
  20. void HThread::blockUntilComplete()
  21. {
  22. PooledThread* parentThread = nullptr;
  23. {
  24. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX_NAMED(parentThread->mMutex, lock);
  37. if (parentThread->mId == mThreadId) // Check again in case it changed
  38. {
  39. while (!parentThread->mIdle)
  40. BS_THREAD_WAIT(parentThread->mWorkerEndedCond, parentThread->mMutex, lock);
  41. }
  42. }
  43. }
  44. PooledThread::PooledThread(const String& name)
  45. :mName(name), mIdle(true), mThreadStarted(false),
  46. mThreadReady(false), mIdleTime(0), mId(0)
  47. { }
  48. PooledThread::~PooledThread()
  49. { }
  50. void PooledThread::initialize()
  51. {
  52. BS_THREAD_CREATE(t, std::bind(&PooledThread::run, this));
  53. mThread = t;
  54. BS_LOCK_MUTEX_NAMED(mMutex, lock);
  55. while(!mThreadStarted)
  56. BS_THREAD_WAIT(mStartedCond, mMutex, lock);
  57. }
  58. void PooledThread::start(std::function<void()> workerMethod, UINT32 id)
  59. {
  60. {
  61. BS_LOCK_MUTEX(mMutex);
  62. mWorkerMethod = workerMethod;
  63. mIdle = false;
  64. mIdleTime = std::time(nullptr);
  65. mThreadReady = true;
  66. mId = id;
  67. }
  68. BS_THREAD_NOTIFY_ONE(mReadyCond);
  69. }
  70. void PooledThread::run()
  71. {
  72. onThreadStarted(mName);
  73. {
  74. BS_LOCK_MUTEX(mMutex);
  75. mThreadStarted = true;
  76. }
  77. BS_THREAD_NOTIFY_ONE(mStartedCond);
  78. while(true)
  79. {
  80. std::function<void()> worker = nullptr;
  81. {
  82. {
  83. BS_LOCK_MUTEX_NAMED(mMutex, lock);
  84. while (!mThreadReady)
  85. BS_THREAD_WAIT(mReadyCond, mMutex, 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. BS_LOCK_MUTEX(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. BS_THREAD_NOTIFY_ONE(mWorkerEndedCond);
  114. }
  115. }
  116. }
  117. void PooledThread::destroy()
  118. {
  119. blockUntilComplete();
  120. {
  121. BS_LOCK_MUTEX(mMutex);
  122. mWorkerMethod = nullptr;
  123. mThreadReady = true;
  124. }
  125. BS_THREAD_NOTIFY_ONE(mReadyCond);
  126. BS_THREAD_JOIN((*mThread));
  127. BS_THREAD_DESTROY(mThread);
  128. }
  129. void PooledThread::blockUntilComplete()
  130. {
  131. BS_LOCK_MUTEX_NAMED(mMutex, lock);
  132. while (!mIdle)
  133. BS_THREAD_WAIT(mWorkerEndedCond, mMutex, lock);
  134. }
  135. bool PooledThread::isIdle()
  136. {
  137. BS_LOCK_MUTEX(mMutex);
  138. return mIdle;
  139. }
  140. time_t PooledThread::idleTime()
  141. {
  142. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX(mMutex);
  171. for(auto& thread : mThreads)
  172. {
  173. destroyThread(thread);
  174. }
  175. mThreads.clear();
  176. }
  177. void ThreadPool::clearUnused()
  178. {
  179. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX(mMutex);
  224. age = ++mAge;
  225. }
  226. if(age == 32)
  227. clearUnused();
  228. PooledThread* newThread = nullptr;
  229. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX(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. BS_LOCK_MUTEX(mMutex);
  272. return (UINT32)mThreads.size();
  273. }
  274. }