CCThreadPool.h 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. #pragma once
  22. //#include "platform/CCPlatformMacros.h"
  23. #include <functional>
  24. #include <memory>
  25. #include <thread>
  26. #include <queue>
  27. #include <mutex>
  28. #include <condition_variable>
  29. #include <vector>
  30. #include <atomic>
  31. namespace cocos2d { namespace experimental {
  32. /**
  33. * @addtogroup base
  34. * @{
  35. */
  36. class ThreadPool
  37. {
  38. public:
  39. enum class TaskType
  40. {
  41. DEFAULT = 0,
  42. NETWORK,
  43. IO,
  44. AUDIO,
  45. USER = 1000
  46. };
  47. /*
  48. * Gets the default thread pool which is a cached thread pool with default parameters.
  49. */
  50. static ThreadPool *getDefaultThreadPool();
  51. /*
  52. * Destroys the default thread pool
  53. */
  54. static void destroyDefaultThreadPool();
  55. /*
  56. * Creates a cached thread pool
  57. * @note The return value has to be delete while it doesn't needed
  58. */
  59. static ThreadPool *newCachedThreadPool(int minThreadNum, int maxThreadNum, int shrinkInterval,
  60. int shrinkStep, int stretchStep);
  61. /*
  62. * Creates a thread pool with fixed thread count
  63. * @note The return value has to be delete while it doesn't needed
  64. */
  65. static ThreadPool *newFixedThreadPool(int threadNum);
  66. /*
  67. * Creates a thread pool with only one thread in the pool, it could be used to execute multiply tasks serially in just one thread.
  68. * @note The return value has to be delete while it doesn't needed
  69. */
  70. static ThreadPool *newSingleThreadPool();
  71. // the destructor waits for all the functions in the queue to be finished
  72. ~ThreadPool();
  73. /* Pushs a task to thread pool
  74. * @param runnable The callback of the task executed in sub thread
  75. * @param type The task type, it's TASK_TYPE_DEFAULT if this argument isn't assigned
  76. * @note This function has to be invoked in cocos thread
  77. */
  78. void pushTask(const std::function<void(int /*threadId*/)>& runnable, TaskType type = TaskType::DEFAULT);
  79. // Stops all tasks, it will remove all tasks in queue
  80. void stopAllTasks();
  81. // Stops some tasks by type
  82. void stopTasksByType(TaskType type);
  83. // Gets the minimum thread numbers
  84. inline int getMinThreadNum() const
  85. { return _minThreadNum; };
  86. // Gets the maximum thread numbers
  87. inline int getMaxThreadNum() const
  88. { return _maxThreadNum; };
  89. // Gets the number of idle threads
  90. int getIdleThreadNum() const;
  91. // Gets the number of initialized threads
  92. inline int getInitedThreadNum() const
  93. { return _initedThreadNum; };
  94. // Gets the task number
  95. int getTaskNum() const;
  96. /*
  97. * Trys to shrink pool
  98. * @note This method is only available for cached thread pool
  99. */
  100. bool tryShrinkPool();
  101. private:
  102. ThreadPool(int minNum, int maxNum);
  103. ThreadPool(const ThreadPool&);
  104. ThreadPool(ThreadPool&&);
  105. ThreadPool& operator=(const ThreadPool&);
  106. ThreadPool& operator=(ThreadPool&&);
  107. void init();
  108. void stop();
  109. void setThread(int tid);
  110. void joinThread(int tid);
  111. void setFixedSize(bool isFixedSize);
  112. void setShrinkInterval(int seconds);
  113. void setShrinkStep(int step);
  114. void setStretchStep(int step);
  115. void stretchPool(int count);
  116. std::vector<std::unique_ptr<std::thread>> _threads;
  117. std::vector<std::shared_ptr<std::atomic<bool>>> _abortFlags;
  118. std::vector<std::shared_ptr<std::atomic<bool>>> _idleFlags;
  119. std::vector<std::shared_ptr<std::atomic<bool>>> _initedFlags;
  120. template<typename T>
  121. class ThreadSafeQueue
  122. {
  123. public:
  124. bool push(T const& value)
  125. {
  126. std::unique_lock<std::mutex> lock(this->mutex);
  127. this->q.push(value);
  128. return true;
  129. }
  130. // deletes the retrieved element, do not use for non integral types
  131. bool pop(T& v)
  132. {
  133. std::unique_lock<std::mutex> lock(this->mutex);
  134. if (this->q.empty())
  135. return false;
  136. v = this->q.front();
  137. this->q.pop();
  138. return true;
  139. }
  140. bool empty() const
  141. {
  142. auto thiz = const_cast<ThreadSafeQueue*>(this);
  143. std::unique_lock<std::mutex> lock(thiz->mutex);
  144. return this->q.empty();
  145. }
  146. size_t size() const
  147. {
  148. auto thiz = const_cast<ThreadSafeQueue*>(this);
  149. std::unique_lock<std::mutex> lock(thiz->mutex);
  150. return this->q.size();
  151. }
  152. private:
  153. std::queue<T> q;
  154. std::mutex mutex;
  155. };
  156. struct Task
  157. {
  158. TaskType type;
  159. std::function<void(int)> *callback;
  160. };
  161. ThreadSafeQueue<Task> _taskQueue;
  162. std::atomic<bool> _isDone;
  163. std::atomic<bool> _isStop;
  164. //FIXME: std::atomic<int> isn't supported by ndk-r10e while compiling with `armeabi` arch.
  165. // So using a mutex here instead.
  166. int _idleThreadNum; // how many threads are waiting
  167. std::mutex _idleThreadNumMutex;
  168. std::mutex _mutex;
  169. std::condition_variable _cv;
  170. int _minThreadNum;
  171. int _maxThreadNum;
  172. int _initedThreadNum;
  173. struct timeval _lastShrinkTime;
  174. float _shrinkInterval;
  175. int _shrinkStep;
  176. int _stretchStep;
  177. bool _isFixedSize;
  178. };
  179. // end of base group
  180. /// @}
  181. }} // namespace cocos2d { namespace experimental {