MCPcopy Create free account
hub / github.com/cocos/cocos-engine / setThread

Method setThread

native/cocos/base/ThreadPool.cpp:337–378  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

335}
336
337void LegacyThreadPool::setThread(int tid) {
338 std::shared_ptr<std::atomic<bool>> abortPtr(
339 _abortFlags[tid]); // a copy of the shared ptr to the flag
340 auto f = [this, tid, abortPtr /* a copy of the shared ptr to the abort */]() {
341 std::atomic<bool> &abort = *abortPtr;
342 Task task;
343 bool isPop = _taskQueue.pop(task);
344 while (true) {
345 while (isPop) { // if there is anything in the queue
346 std::unique_ptr<std::function<void(int)>> func(
347 task.callback); // at return, delete the function even if an exception occurred
348 (*task.callback)(tid);
349 if (abort) {
350 return; // the thread is wanted to stop, return even if the queue is not empty yet
351 }
352
353 isPop = _taskQueue.pop(task);
354 }
355 // the queue is empty here, wait for the next command
356 std::unique_lock<std::mutex> lock(_mutex);
357 _idleThreadNumMutex.lock();
358 ++_idleThreadNum;
359 _idleThreadNumMutex.unlock();
360
361 *_idleFlags[tid] = true;
362 _cv.wait(lock, [this, &task, &isPop, &abort]() {
363 isPop = _taskQueue.pop(task);
364 return isPop || _isDone || abort;
365 });
366 *_idleFlags[tid] = false;
367 _idleThreadNumMutex.lock();
368 --_idleThreadNum;
369 _idleThreadNumMutex.unlock();
370
371 if (!isPop) {
372 return; // if the queue is empty and isDone == true or *flag then return
373 }
374 }
375 };
376 _threads[tid].reset(
377 ccnew std::thread(f)); // compiler may not support std::make_unique()
378}
379
380} // namespace cc

Callers

nothing calls this directly

Calls 4

lockMethod · 0.80
resetMethod · 0.65
popMethod · 0.45
waitMethod · 0.45

Tested by

no test coverage detected