CCThreadPool.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /****************************************************************************
  2. Copyright (c) 2016-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. Inspired by https://github.com/vit-vit/CTPL
  20. ****************************************************************************/
  21. #include "base/CCThreadPool.h"
  22. #ifdef __ANDROID__
  23. #include <android/log.h>
  24. #define LOG_TAG "ThreadPool"
  25. #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,__VA_ARGS__)
  26. #else
  27. #define LOGD(...) printf(__VA_ARGS__)
  28. #endif
  29. namespace cocos2d {
  30. #define DEFAULT_THREAD_POOL_MIN_NUM (4)
  31. #define DEFAULT_THREAD_POOL_MAX_NUM (20)
  32. #define DEFAULT_SHRINK_INTERVAL (5.0f)
  33. #define DEFAULT_SHRINK_STEP (2)
  34. #define DEFAULT_STRETCH_STEP (2)
  35. static ThreadPool *__defaultThreadPool = nullptr;
  36. ThreadPool *ThreadPool::getDefaultThreadPool()
  37. {
  38. if (__defaultThreadPool == nullptr)
  39. {
  40. __defaultThreadPool = newCachedThreadPool(DEFAULT_THREAD_POOL_MIN_NUM,
  41. DEFAULT_THREAD_POOL_MAX_NUM,
  42. DEFAULT_SHRINK_INTERVAL, DEFAULT_SHRINK_STEP,
  43. DEFAULT_STRETCH_STEP);
  44. }
  45. return __defaultThreadPool;
  46. }
  47. void ThreadPool::destroyDefaultThreadPool()
  48. {
  49. delete __defaultThreadPool;
  50. __defaultThreadPool = nullptr;
  51. }
  52. ThreadPool *ThreadPool::newCachedThreadPool(int minThreadNum, int maxThreadNum, int shrinkInterval,
  53. int shrinkStep, int stretchStep)
  54. {
  55. ThreadPool *pool = new(std::nothrow) ThreadPool(minThreadNum, maxThreadNum);
  56. if (pool != nullptr)
  57. {
  58. pool->setFixedSize(false);
  59. pool->setShrinkInterval(shrinkInterval);
  60. pool->setShrinkStep(shrinkStep);
  61. pool->setStretchStep(stretchStep);
  62. }
  63. return pool;
  64. }
  65. ThreadPool *ThreadPool::newFixedThreadPool(int threadNum)
  66. {
  67. ThreadPool *pool = new(std::nothrow) ThreadPool(threadNum, threadNum);
  68. if (pool != nullptr)
  69. {
  70. pool->setFixedSize(true);
  71. }
  72. return pool;
  73. }
  74. ThreadPool *ThreadPool::newSingleThreadPool()
  75. {
  76. ThreadPool *pool = new(std::nothrow) ThreadPool(1, 1);
  77. if (pool != nullptr)
  78. {
  79. pool->setFixedSize(true);
  80. }
  81. return pool;
  82. }
  83. ThreadPool::ThreadPool(int minNum, int maxNum)
  84. : _isDone(false), _isStop(false), _idleThreadNum(0), _minThreadNum(minNum),
  85. _maxThreadNum(maxNum), _initedThreadNum(0), _shrinkInterval(DEFAULT_SHRINK_INTERVAL),
  86. _shrinkStep(DEFAULT_SHRINK_STEP), _stretchStep(DEFAULT_STRETCH_STEP),
  87. _isFixedSize(false)
  88. {
  89. init();
  90. }
  91. // the destructor waits for all the functions in the queue to be finished
  92. ThreadPool::~ThreadPool()
  93. {
  94. stop();
  95. }
  96. // number of idle threads
  97. int ThreadPool::getIdleThreadNum() const
  98. {
  99. ThreadPool* thiz = const_cast<ThreadPool*>(this);
  100. std::lock_guard<std::mutex> lk(thiz->_idleThreadNumMutex);
  101. return _idleThreadNum;
  102. }
  103. void ThreadPool::init()
  104. {
  105. gettimeofday(&_lastShrinkTime, nullptr);
  106. _maxThreadNum = std::max(_minThreadNum, _maxThreadNum);
  107. _threads.resize(_maxThreadNum);
  108. _abortFlags.resize(_maxThreadNum);
  109. _idleFlags.resize(_maxThreadNum);
  110. _initedFlags.resize(_maxThreadNum);
  111. for (int i = 0; i < _maxThreadNum; ++i)
  112. {
  113. _idleFlags[i] = std::make_shared<std::atomic<bool>>(false);
  114. if (i < _minThreadNum)
  115. {
  116. _abortFlags[i] = std::make_shared<std::atomic<bool>>(false);
  117. setThread(i);
  118. _initedFlags[i] = std::make_shared<std::atomic<bool>>(true);
  119. ++_initedThreadNum;
  120. }
  121. else
  122. {
  123. _abortFlags[i] = std::make_shared<std::atomic<bool>>(true);
  124. _initedFlags[i] = std::make_shared<std::atomic<bool>>(false);
  125. }
  126. }
  127. }
  128. bool ThreadPool::tryShrinkPool()
  129. {
  130. LOGD("shrink pool, _idleThreadNum = %d \n", getIdleThreadNum());
  131. struct timeval before;
  132. gettimeofday(&before, nullptr);
  133. std::vector<int> threadIDsToJoin;
  134. int maxThreadNumToJoin = std::min(_initedThreadNum - _minThreadNum, _shrinkStep);
  135. for (int i = 0; i < _maxThreadNum; ++i)
  136. {
  137. if ((int)threadIDsToJoin.size() >= maxThreadNumToJoin)
  138. {
  139. break;
  140. }
  141. if (*_idleFlags[i])
  142. {
  143. *_abortFlags[i] = true;
  144. threadIDsToJoin.push_back(i);
  145. }
  146. }
  147. {
  148. // stop the detached threads that were waiting
  149. std::unique_lock<std::mutex> lock(_mutex);
  150. _cv.notify_all();
  151. }
  152. for (const auto& threadID : threadIDsToJoin)
  153. { // wait for the computing threads to finish
  154. if (_threads[threadID]->joinable())
  155. {
  156. _threads[threadID]->join();
  157. }
  158. _threads[threadID].reset();
  159. *_initedFlags[threadID] = false;
  160. --_initedThreadNum;
  161. }
  162. struct timeval after;
  163. gettimeofday(&after, nullptr);
  164. float seconds = (after.tv_sec - before.tv_sec) + (after.tv_usec - before.tv_usec) / 1000000.0f;
  165. LOGD("shrink %d threads, waste: %f seconds\n", (int) threadIDsToJoin.size(), seconds);
  166. if (_initedThreadNum <= _minThreadNum)
  167. return true;
  168. return false;
  169. }
  170. void ThreadPool::stretchPool(int count)
  171. {
  172. struct timeval before;
  173. gettimeofday(&before, nullptr);
  174. int oldThreadCount = _initedThreadNum;
  175. int newThreadCount = 0;
  176. for (int i = 0; i < _maxThreadNum; ++i)
  177. {
  178. if (!*_initedFlags[i])
  179. {
  180. *_abortFlags[i] = false;
  181. setThread(i);
  182. *_initedFlags[i] = true;
  183. ++_initedThreadNum;
  184. if (++newThreadCount >= count)
  185. {
  186. break;
  187. }
  188. }
  189. }
  190. if (newThreadCount > 0)
  191. {
  192. struct timeval after;
  193. gettimeofday(&after, nullptr);
  194. float seconds =
  195. (after.tv_sec - before.tv_sec) + (after.tv_usec - before.tv_usec) / 1000000.0f;
  196. LOGD("stretch pool from %d to %d, waste %f seconds\n", oldThreadCount, _initedThreadNum,
  197. seconds);
  198. }
  199. }
  200. void ThreadPool::pushTask(const std::function<void(int)>& runnable,
  201. TaskType type/* = DEFAULT*/)
  202. {
  203. if (!_isFixedSize)
  204. {
  205. _idleThreadNumMutex.lock();
  206. int idleNum = _idleThreadNum;
  207. _idleThreadNumMutex.unlock();
  208. if (idleNum > _minThreadNum)
  209. {
  210. if (_taskQueue.empty())
  211. {
  212. struct timeval now;
  213. gettimeofday(&now, nullptr);
  214. float seconds = (now.tv_sec - _lastShrinkTime.tv_sec) +
  215. (now.tv_usec - _lastShrinkTime.tv_usec) / 1000000.0f;
  216. if (seconds > _shrinkInterval)
  217. {
  218. tryShrinkPool();
  219. _lastShrinkTime = now;
  220. }
  221. }
  222. }
  223. else if (idleNum == 0)
  224. {
  225. stretchPool(_stretchStep);
  226. }
  227. }
  228. auto callback = new(std::nothrow) std::function<void(int)>([runnable](int tid) {
  229. runnable(tid);
  230. });
  231. Task task;
  232. task.type = type;
  233. task.callback = callback;
  234. _taskQueue.push(std::move(task));
  235. {
  236. std::unique_lock<std::mutex> lock(_mutex);
  237. _cv.notify_one();
  238. }
  239. }
  240. void ThreadPool::stopAllTasks()
  241. {
  242. Task task;
  243. while (_taskQueue.pop(task))
  244. {
  245. delete task.callback; // empty the queue
  246. }
  247. }
  248. void ThreadPool::stopTasksByType(TaskType type)
  249. {
  250. Task task;
  251. std::vector<Task> notStopTasks;
  252. notStopTasks.reserve(_taskQueue.size());
  253. while (_taskQueue.pop(task))
  254. {
  255. if (task.type == type)
  256. {// Delete the task from queue
  257. delete task.callback;
  258. }
  259. else
  260. {// If task type isn't match, push it into a vector, then insert to task queue again
  261. notStopTasks.push_back(task);
  262. }
  263. }
  264. if (!notStopTasks.empty())
  265. {
  266. for (const auto& t : notStopTasks)
  267. {
  268. _taskQueue.push(t);
  269. }
  270. }
  271. }
  272. void ThreadPool::joinThread(int tid)
  273. {
  274. if (tid < 0 || tid >= (int)_threads.size())
  275. {
  276. LOGD("Invalid thread id %d\n", tid);
  277. return;
  278. }
  279. // wait for the computing threads to finish
  280. if (*_initedFlags[tid] && _threads[tid]->joinable())
  281. {
  282. _threads[tid]->join();
  283. *_initedFlags[tid] = false;
  284. --_initedThreadNum;
  285. }
  286. }
  287. int ThreadPool::getTaskNum() const
  288. {
  289. return (int) _taskQueue.size();
  290. }
  291. void ThreadPool::setFixedSize(bool isFixedSize)
  292. {
  293. _isFixedSize = isFixedSize;
  294. }
  295. void ThreadPool::setShrinkInterval(int seconds)
  296. {
  297. if (seconds >= 0)
  298. _shrinkInterval = seconds;
  299. }
  300. void ThreadPool::setShrinkStep(int step)
  301. {
  302. if (step > 0)
  303. _shrinkStep = step;
  304. }
  305. void ThreadPool::setStretchStep(int step)
  306. {
  307. if (step > 0)
  308. _stretchStep = step;
  309. }
  310. void ThreadPool::stop()
  311. {
  312. if (_isDone || _isStop)
  313. return;
  314. _isDone = true; // give the waiting threads a command to finish
  315. {
  316. std::unique_lock<std::mutex> lock(_mutex);
  317. _cv.notify_all(); // stop all waiting threads
  318. }
  319. for (int i = 0, n = static_cast<int>(_threads.size()); i < n; ++i)
  320. {
  321. joinThread(i);
  322. }
  323. // if there were no threads in the pool but some functors in the queue, the functors are not deleted by the threads
  324. // therefore delete them here
  325. stopAllTasks();
  326. _threads.clear();
  327. _abortFlags.clear();
  328. }
  329. void ThreadPool::setThread(int tid)
  330. {
  331. std::shared_ptr<std::atomic<bool>> abort_ptr(
  332. _abortFlags[tid]); // a copy of the shared ptr to the flag
  333. auto f = [this, tid, abort_ptr/* a copy of the shared ptr to the abort */]() {
  334. std::atomic<bool>& abort = *abort_ptr;
  335. Task task;
  336. bool isPop = _taskQueue.pop(task);
  337. while (true)
  338. {
  339. while (isPop)
  340. { // if there is anything in the queue
  341. std::unique_ptr<std::function<void(int)>> func(
  342. task.callback); // at return, delete the function even if an exception occurred
  343. (*task.callback)(tid);
  344. if (abort)
  345. return; // the thread is wanted to stop, return even if the queue is not empty yet
  346. else
  347. isPop = _taskQueue.pop(task);
  348. }
  349. // the queue is empty here, wait for the next command
  350. std::unique_lock<std::mutex> lock(_mutex);
  351. _idleThreadNumMutex.lock();
  352. ++_idleThreadNum;
  353. _idleThreadNumMutex.unlock();
  354. *_idleFlags[tid] = true;
  355. _cv.wait(lock, [this, &task, &isPop, &abort]() {
  356. isPop = _taskQueue.pop(task);
  357. return isPop || _isDone || abort;
  358. });
  359. *_idleFlags[tid] = false;
  360. _idleThreadNumMutex.lock();
  361. --_idleThreadNum;
  362. _idleThreadNumMutex.unlock();
  363. if (!isPop)
  364. return; // if the queue is empty and isDone == true or *flag then return
  365. }
  366. };
  367. _threads[tid].reset(
  368. new(std::nothrow) std::thread(f)); // compiler may not support std::make_unique()
  369. }
  370. } // namespace cocos2d {