Files
cocos-engine/native/extensions/assets-manager/AsyncTaskPool.h
qiuguohua eeb9d5c689 Merge the code of v3.3.1 platform adaptation layer into the development branch (#3958)
* 1、Merge platform adaptation layer code into the development branch
2、It passed the test in windows and ohos system

* 1、Merge platform adaptation layer code into the development branch
2、It passed the test in windows and ohos system

* 1、Fix github compile windows error

* 1、Fix github compile windows error

* 1. Adjust the code format;
2. Fix js automatic generation binding
3. Adjust github CI compilation

* 1. Adjust the code format;
2. Fix js automatic generation binding
3. Adjust github CI compilation

* Solve mac and ios compilation failure

* Fix the problem of compilation of Windows-side simulator

* 1. Adapt the simulator to a new adaptation layer;
2. Fix the compilation warning of ios, and the implicit conversion failed;
3. Fix the mac compilation error, due to the problem of adding the link identification -all_load;

* 1.Add the isDisplayStats and setDisplayStats method to the screen interface

* Fix clang-tidy compilation warning

* Fix clang-tidy compilation warning

* Repair the emulator, compatible with mac and win

* 1、Repair detailed errors, including name modification and calling method modification
2、Delete redundant files in the template directory
3、Change the vibrate interface to vibrator
4、Fix word spelling errors

* Rename interfaces to modules

* Replace CC_ASSERT with CCASSERT

* Replace CC_ASSERT with CCASSERT

Co-authored-by: qiuguohua <>
2021-10-27 10:51:02 +08:00

208 lines
6.5 KiB
C++

/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "application/ApplicationManager.h"
#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <thread>
#include <vector>
/**
* @addtogroup base
* @{
*/
namespace cc {
/**
* @class AsyncTaskPool
* @brief This class allows to perform background operations without having to manipulate threads.
* @js NA
*/
class CC_DLL AsyncTaskPool {
public:
using TaskCallBack = std::function<void(void *)>;
enum class TaskType {
TASK_IO,
TASK_NETWORK,
TASK_OTHER,
TASK_MAX_TYPE,
};
/**
* Returns the shared instance of the async task pool.
*/
static AsyncTaskPool *getInstance();
/**
* Destroys the async task pool.
*/
static void destroyInstance();
AsyncTaskPool();
~AsyncTaskPool();
/**
* Stop tasks.
*
* @param type Task type you want to stop.
*/
void stopTasks(TaskType type);
/**
* Enqueue a asynchronous task.
*
* @param type task type is io task, network task or others, each type of task has a thread to deal with it.
* @param callback callback when the task is finished. The callback is called in the main thread instead of task thread.
* @param callbackParam parameter used by the callback.
* @param f task can be lambda function.
* @lua NA
*/
template <class F>
inline void enqueue(TaskType type, const TaskCallBack &callback, void *callbackParam, F &&f);
protected:
// thread tasks internally used
class ThreadTasks {
struct AsyncTaskCallBack {
TaskCallBack callback;
void * callbackParam;
};
public:
ThreadTasks() {
_thread = std::thread(
[this] {
for (;;) {
std::function<void()> task;
AsyncTaskCallBack callback;
{
std::unique_lock<std::mutex> lock(this->_queueMutex);
this->_condition.wait(lock,
[this] { return this->_stop || !this->_tasks.empty(); });
if (this->_stop && this->_tasks.empty()) {
return;
}
task = std::move(this->_tasks.front());
callback = std::move(this->_taskCallBacks.front());
this->_tasks.pop();
this->_taskCallBacks.pop();
}
task();
CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([&, callback] { callback.callback(callback.callbackParam); });
}
});
}
~ThreadTasks() {
{
std::unique_lock<std::mutex> lock(_queueMutex);
_stop = true;
while (!_tasks.empty()) {
_tasks.pop();
}
while (!_taskCallBacks.empty()) {
_taskCallBacks.pop();
}
}
_condition.notify_all();
_thread.join();
}
void clear() {
std::unique_lock<std::mutex> lock(_queueMutex);
while (!_tasks.empty()) {
_tasks.pop();
}
while (!_taskCallBacks.empty()) {
_taskCallBacks.pop();
}
}
template <class F>
void enqueue(const TaskCallBack &callback, void *callbackParam, F &&f) {
auto task = f; //std::bind(std::forward<F>(f), std::forward<Args>(args)...);
{
std::unique_lock<std::mutex> lock(_queueMutex);
// don't allow enqueueing after stopping the pool
if (_stop) {
CC_ASSERT(0 && "already stop");
return;
}
AsyncTaskCallBack taskCallBack;
taskCallBack.callback = callback;
taskCallBack.callbackParam = callbackParam;
_tasks.emplace([task]() { task(); });
_taskCallBacks.emplace(taskCallBack);
}
_condition.notify_one();
}
private:
// need to keep track of thread so we can join them
std::thread _thread;
// the task queue
std::queue<std::function<void()>> _tasks;
std::queue<AsyncTaskCallBack> _taskCallBacks;
// synchronization
std::mutex _queueMutex;
std::condition_variable _condition;
bool _stop{false};
};
//tasks
ThreadTasks _threadTasks[static_cast<int>(TaskType::TASK_MAX_TYPE)];
static AsyncTaskPool *sAsyncTaskPool;
};
inline void AsyncTaskPool::stopTasks(TaskType type) {
auto &threadTask = _threadTasks[static_cast<int>(type)];
threadTask.clear();
}
template <class F>
inline void AsyncTaskPool::enqueue(AsyncTaskPool::TaskType type, const TaskCallBack &callback, void *callbackParam, F &&f) {
auto &threadTask = _threadTasks[static_cast<int>(type)];
threadTask.enqueue(callback, callbackParam, f);
}
} // namespace cc
// end group
/// @}