CCThreadPool.cpp 12 KB

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