diff --git a/native/cocos/base/Scheduler.cpp b/native/cocos/base/Scheduler.cpp index 402fb7608ee..2d6319aaf8d 100644 --- a/native/cocos/base/Scheduler.cpp +++ b/native/cocos/base/Scheduler.cpp @@ -338,7 +338,6 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() { // auto beginTime = std::chrono::steady_clock::now(); auto nowTime = beginTime; - bool doJob = true; // Testing size is faster than locking / unlocking. // And almost never there will be functions scheduled to be called. @@ -347,24 +346,22 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() { // fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock. auto temp = std::move(_functionsToPerform); _performMutex.unlock(); - - for (auto &&function : temp) { - if (doJob) { - nowTime = std::chrono::steady_clock::now(); - auto passedMS = std::chrono::duration_cast(nowTime - beginTime).count(); - // If the callbacks takes more than 16ms, delay the remaining jobs to next frame. - if (passedMS > 16) { - doJob = false; - } + + auto iter = temp.begin(); + for (; iter != temp.end(); ++iter) { + nowTime = std::chrono::steady_clock::now(); + auto passedMS = std::chrono::duration_cast(nowTime - beginTime).count(); + // If the callbacks takes more than 16ms, delay the remaining jobs to next frame. + if (passedMS > 16) { + break; } - if (doJob) { - function(); - } else { - _performMutex.lock(); - _functionsToPerform.emplace_back(std::move(function)); - _performMutex.unlock(); - } + (*iter)(); + } + + std::lock_guard lk(_performMutex); + for (; iter != temp.end(); ++iter) { + _functionsToPerform.emplace_back(std::move(*iter)); } } }