CCAsyncTaskPool.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /****************************************************************************
  2. Copyright (c) 2013-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #ifndef __CCSYNC_TASK_POOL_H_
  22. #define __CCSYNC_TASK_POOL_H_
  23. #include "platform/CCPlatformMacros.h"
  24. #include "base/CCDirector.h"
  25. #include "base/CCScheduler.h"
  26. #include <vector>
  27. #include <queue>
  28. #include <memory>
  29. #include <thread>
  30. #include <mutex>
  31. #include <condition_variable>
  32. #include <future>
  33. #include <functional>
  34. #include <stdexcept>
  35. /**
  36. * @addtogroup base
  37. * @{
  38. */
  39. NS_CC_BEGIN
  40. /**
  41. * @class AsyncTaskPool
  42. * @brief This class allows to perform background operations without having to manipulate threads.
  43. * @js NA
  44. */
  45. class CC_DLL AsyncTaskPool
  46. {
  47. public:
  48. typedef std::function<void(void*)> TaskCallBack;
  49. enum class TaskType
  50. {
  51. TASK_IO,
  52. TASK_NETWORK,
  53. TASK_OTHER,
  54. TASK_MAX_TYPE,
  55. };
  56. /**
  57. * Returns the shared instance of the async task pool.
  58. */
  59. static AsyncTaskPool* getInstance();
  60. /**
  61. * Destroys the async task pool.
  62. */
  63. static void destroyInstance();
  64. /** @deprecated Use method destroyInstance() instead. */
  65. CC_DEPRECATED_ATTRIBUTE static void destoryInstance() { return destroyInstance(); }
  66. /**
  67. * Stop tasks.
  68. *
  69. * @param type Task type you want to stop.
  70. */
  71. void stopTasks(TaskType type);
  72. /**
  73. * Enqueue a asynchronous task.
  74. *
  75. * @param type task type is io task, network task or others, each type of task has a thread to deal with it.
  76. * @param callback callback when the task is finished. The callback is called in the main thread instead of task thread.
  77. * @param callbackParam parameter used by the callback.
  78. * @param task: task can be lambda function to be performed off thread.
  79. * @lua NA
  80. */
  81. void enqueue(TaskType type, TaskCallBack callback, void* callbackParam, std::function<void()> task);
  82. /**
  83. * Enqueue a asynchronous task.
  84. *
  85. * @param type task type is io task, network task or others, each type of task has a thread to deal with it.
  86. * @param task: task can be lambda function to be performed off thread.
  87. * @lua NA
  88. */
  89. void enqueue(AsyncTaskPool::TaskType type, std::function<void()> task);
  90. CC_CONSTRUCTOR_ACCESS:
  91. AsyncTaskPool();
  92. ~AsyncTaskPool();
  93. protected:
  94. // thread tasks internally used
  95. class ThreadTasks {
  96. struct AsyncTaskCallBack
  97. {
  98. TaskCallBack callback;
  99. void* callbackParam;
  100. };
  101. public:
  102. ThreadTasks()
  103. : _stop(false)
  104. {
  105. _thread = std::thread(
  106. [this]
  107. {
  108. for(;;)
  109. {
  110. std::function<void()> task;
  111. AsyncTaskCallBack callback;
  112. {
  113. std::unique_lock<std::mutex> lock(this->_queueMutex);
  114. this->_condition.wait(lock,
  115. [this]{ return this->_stop || !this->_tasks.empty(); });
  116. if(this->_stop && this->_tasks.empty())
  117. return;
  118. task = std::move(this->_tasks.front());
  119. callback = std::move(this->_taskCallBacks.front());
  120. this->_tasks.pop();
  121. this->_taskCallBacks.pop();
  122. }
  123. task();
  124. Director::getInstance()->getScheduler()->performFunctionInCocosThread(std::bind(callback.callback, callback.callbackParam));
  125. }
  126. }
  127. );
  128. }
  129. ~ThreadTasks()
  130. {
  131. {
  132. std::unique_lock<std::mutex> lock(_queueMutex);
  133. _stop = true;
  134. while(_tasks.size())
  135. _tasks.pop();
  136. while (_taskCallBacks.size())
  137. _taskCallBacks.pop();
  138. }
  139. _condition.notify_all();
  140. _thread.join();
  141. }
  142. void clear()
  143. {
  144. std::unique_lock<std::mutex> lock(_queueMutex);
  145. while(_tasks.size())
  146. _tasks.pop();
  147. while (_taskCallBacks.size())
  148. _taskCallBacks.pop();
  149. }
  150. void enqueue(TaskCallBack callback, void* callbackParam, std::function<void()> task)
  151. {
  152. AsyncTaskCallBack taskCallBack;
  153. taskCallBack.callback = std::move(callback);
  154. taskCallBack.callbackParam = callbackParam;
  155. {
  156. std::unique_lock<std::mutex> lock(_queueMutex);
  157. // don't allow enqueueing after stopping the pool
  158. if(_stop)
  159. {
  160. CC_ASSERT(0 && "already stop");
  161. return;
  162. }
  163. _tasks.push(std::move(task));
  164. _taskCallBacks.push(std::move(taskCallBack));
  165. }
  166. _condition.notify_one();
  167. }
  168. private:
  169. // need to keep track of thread so we can join them
  170. std::thread _thread;
  171. // the task queue
  172. std::queue< std::function<void()> > _tasks;
  173. std::queue<AsyncTaskCallBack> _taskCallBacks;
  174. // synchronization
  175. std::mutex _queueMutex;
  176. std::condition_variable _condition;
  177. bool _stop;
  178. };
  179. //tasks
  180. ThreadTasks _threadTasks[int(TaskType::TASK_MAX_TYPE)];
  181. static AsyncTaskPool* s_asyncTaskPool;
  182. };
  183. inline void AsyncTaskPool::stopTasks(TaskType type)
  184. {
  185. auto& threadTask = _threadTasks[(int)type];
  186. threadTask.clear();
  187. }
  188. inline void AsyncTaskPool::enqueue(AsyncTaskPool::TaskType type, TaskCallBack callback, void* callbackParam, std::function<void()> task)
  189. {
  190. auto& threadTask = _threadTasks[(int)type];
  191. threadTask.enqueue(std::move(callback), callbackParam, std::move(task));
  192. }
  193. inline void AsyncTaskPool::enqueue(AsyncTaskPool::TaskType type, std::function<void()> task)
  194. {
  195. enqueue(type, [](void*) {}, nullptr, std::move(task));
  196. }
  197. NS_CC_END
  198. // end group
  199. /// @}
  200. #endif //__CCSYNC_TASK_POOL_H_