| 333 | } |
| 334 | |
| 335 | void Scheduler::runFunctionsToBePerformedInCocosThread() { |
| 336 | // |
| 337 | // Functions allocated from another thread |
| 338 | // |
| 339 | auto beginTime = std::chrono::steady_clock::now(); |
| 340 | auto nowTime = beginTime; |
| 341 | |
| 342 | // Testing size is faster than locking / unlocking. |
| 343 | // And almost never there will be functions scheduled to be called. |
| 344 | if (!_functionsToPerform.empty()) { |
| 345 | _performMutex.lock(); |
| 346 | // 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. |
| 347 | auto temp = std::move(_functionsToPerform); |
| 348 | _performMutex.unlock(); |
| 349 | |
| 350 | auto iter = temp.begin(); |
| 351 | for (; iter != temp.end(); ++iter) { |
| 352 | nowTime = std::chrono::steady_clock::now(); |
| 353 | auto passedMS = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - beginTime).count(); |
| 354 | // If the callbacks takes more than 16ms, delay the remaining jobs to next frame. |
| 355 | if (passedMS > 16) { |
| 356 | break; |
| 357 | } |
| 358 | |
| 359 | (*iter)(); |
| 360 | } |
| 361 | |
| 362 | std::lock_guard<std::mutex> lk(_performMutex); |
| 363 | _functionsToPerform.insert(_functionsToPerform.begin(), std::make_move_iterator(iter), std::make_move_iterator(temp.end())); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // main loop |
| 368 | void Scheduler::update(float dt) { |