Skip to content

Commit

Permalink
Update runFunctionsToBePerformedInCocosThread
Browse files Browse the repository at this point in the history
  • Loading branch information
dumganhar committed Jul 31, 2024
1 parent 66083a7 commit d2dbb09
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions native/cocos/base/Scheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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<std::chrono::milliseconds>(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<std::chrono::milliseconds>(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<std::mutex> lk(_performMutex);
for (; iter != temp.end(); ++iter) {
_functionsToPerform.emplace_back(std::move(*iter));
}
}
}
Expand Down

0 comments on commit d2dbb09

Please sign in to comment.