worker_thread_pool.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. /**************************************************************************/
  2. /* worker_thread_pool.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "worker_thread_pool.h"
  31. #include "core/object/script_language.h"
  32. #include "core/os/os.h"
  33. #include "core/os/safe_binary_mutex.h"
  34. #include "core/os/thread_safe.h"
  35. WorkerThreadPool::Task *const WorkerThreadPool::ThreadData::YIELDING = (Task *)1;
  36. HashMap<StringName, WorkerThreadPool *> WorkerThreadPool::named_pools;
  37. void WorkerThreadPool::Task::free_template_userdata() {
  38. ERR_FAIL_NULL(template_userdata);
  39. ERR_FAIL_NULL(native_func_userdata);
  40. BaseTemplateUserdata *btu = (BaseTemplateUserdata *)native_func_userdata;
  41. memdelete(btu);
  42. }
  43. WorkerThreadPool *WorkerThreadPool::singleton = nullptr;
  44. #ifdef THREADS_ENABLED
  45. thread_local WorkerThreadPool::UnlockableLocks WorkerThreadPool::unlockable_locks[MAX_UNLOCKABLE_LOCKS];
  46. #endif
  47. void WorkerThreadPool::_process_task(Task *p_task) {
  48. #ifdef THREADS_ENABLED
  49. int pool_thread_index = thread_ids[Thread::get_caller_id()];
  50. ThreadData &curr_thread = threads[pool_thread_index];
  51. Task *prev_task = nullptr; // In case this is recursively called.
  52. bool safe_for_nodes_backup = is_current_thread_safe_for_nodes();
  53. CallQueue *call_queue_backup = MessageQueue::get_singleton() != MessageQueue::get_main_singleton() ? MessageQueue::get_singleton() : nullptr;
  54. {
  55. // Tasks must start with these at default values. They are free to set-and-forget otherwise.
  56. set_current_thread_safe_for_nodes(false);
  57. MessageQueue::set_thread_singleton_override(nullptr);
  58. // Since the WorkerThreadPool is started before the script server,
  59. // its pre-created threads can't have ScriptServer::thread_enter() called on them early.
  60. // Therefore, we do it late at the first opportunity, so in case the task
  61. // about to be run uses scripting, guarantees are held.
  62. ScriptServer::thread_enter();
  63. task_mutex.lock();
  64. p_task->pool_thread_index = pool_thread_index;
  65. prev_task = curr_thread.current_task;
  66. curr_thread.current_task = p_task;
  67. if (p_task->pending_notify_yield_over) {
  68. curr_thread.yield_is_over = true;
  69. }
  70. task_mutex.unlock();
  71. }
  72. #endif
  73. #ifdef THREADS_ENABLED
  74. bool low_priority = p_task->low_priority;
  75. #endif
  76. if (p_task->group) {
  77. // Handling a group
  78. bool do_post = false;
  79. while (true) {
  80. uint32_t work_index = p_task->group->index.postincrement();
  81. if (work_index >= p_task->group->max) {
  82. break;
  83. }
  84. if (p_task->native_group_func) {
  85. p_task->native_group_func(p_task->native_func_userdata, work_index);
  86. } else if (p_task->template_userdata) {
  87. p_task->template_userdata->callback_indexed(work_index);
  88. } else {
  89. p_task->callable.call(work_index);
  90. }
  91. // This is the only way to ensure posting is done when all tasks are really complete.
  92. uint32_t completed_amount = p_task->group->completed_index.increment();
  93. if (completed_amount == p_task->group->max) {
  94. do_post = true;
  95. }
  96. }
  97. if (do_post && p_task->template_userdata) {
  98. memdelete(p_task->template_userdata); // This is no longer needed at this point, so get rid of it.
  99. }
  100. if (do_post) {
  101. p_task->group->done_semaphore.post();
  102. p_task->group->completed.set_to(true);
  103. }
  104. uint32_t max_users = p_task->group->tasks_used + 1; // Add 1 because the thread waiting for it is also user. Read before to avoid another thread freeing task after increment.
  105. uint32_t finished_users = p_task->group->finished.increment();
  106. if (finished_users == max_users) {
  107. // Get rid of the group, because nobody else is using it.
  108. MutexLock task_lock(task_mutex);
  109. group_allocator.free(p_task->group);
  110. }
  111. // For groups, tasks get rid of themselves.
  112. task_mutex.lock();
  113. task_allocator.free(p_task);
  114. } else {
  115. if (p_task->native_func) {
  116. p_task->native_func(p_task->native_func_userdata);
  117. } else if (p_task->template_userdata) {
  118. p_task->template_userdata->callback();
  119. memdelete(p_task->template_userdata);
  120. } else {
  121. p_task->callable.call();
  122. }
  123. task_mutex.lock();
  124. p_task->completed = true;
  125. p_task->pool_thread_index = -1;
  126. if (p_task->waiting_user) {
  127. p_task->done_semaphore.post(p_task->waiting_user);
  128. }
  129. // Let awaiters know.
  130. for (uint32_t i = 0; i < threads.size(); i++) {
  131. if (threads[i].awaited_task == p_task) {
  132. threads[i].cond_var.notify_one();
  133. threads[i].signaled = true;
  134. }
  135. }
  136. }
  137. #ifdef THREADS_ENABLED
  138. {
  139. curr_thread.current_task = prev_task;
  140. if (low_priority) {
  141. low_priority_threads_used--;
  142. if (_try_promote_low_priority_task()) {
  143. if (prev_task) { // Otherwise, this thread will catch it.
  144. _notify_threads(&curr_thread, 1, 0);
  145. }
  146. }
  147. }
  148. task_mutex.unlock();
  149. }
  150. set_current_thread_safe_for_nodes(safe_for_nodes_backup);
  151. MessageQueue::set_thread_singleton_override(call_queue_backup);
  152. #endif
  153. }
  154. void WorkerThreadPool::_thread_function(void *p_user) {
  155. ThreadData *thread_data = (ThreadData *)p_user;
  156. Thread::set_name(vformat("WorkerThread %d", thread_data->index));
  157. while (true) {
  158. Task *task_to_process = nullptr;
  159. {
  160. // Create the lock outside the inner loop so it isn't needlessly unlocked and relocked
  161. // when no task was found to process, and the loop is re-entered.
  162. MutexLock lock(thread_data->pool->task_mutex);
  163. while (true) {
  164. bool exit = thread_data->pool->_handle_runlevel(thread_data, lock);
  165. if (unlikely(exit)) {
  166. return;
  167. }
  168. thread_data->signaled = false;
  169. if (!thread_data->pool->task_queue.first()) {
  170. // There wasn't a task available yet.
  171. // Let's wait for the next notification, then recheck.
  172. thread_data->cond_var.wait(lock);
  173. continue;
  174. }
  175. // Got a task to process! Remove it from the queue, then break into the task handling section.
  176. task_to_process = thread_data->pool->task_queue.first()->self();
  177. thread_data->pool->task_queue.remove(thread_data->pool->task_queue.first());
  178. break;
  179. }
  180. }
  181. DEV_ASSERT(task_to_process);
  182. thread_data->pool->_process_task(task_to_process);
  183. }
  184. }
  185. void WorkerThreadPool::_post_tasks(Task **p_tasks, uint32_t p_count, bool p_high_priority, MutexLock<BinaryMutex> &p_lock) {
  186. // Fall back to processing on the calling thread if there are no worker threads.
  187. // Separated into its own variable to make it easier to extend this logic
  188. // in custom builds.
  189. bool process_on_calling_thread = threads.is_empty();
  190. if (process_on_calling_thread) {
  191. p_lock.temp_unlock();
  192. for (uint32_t i = 0; i < p_count; i++) {
  193. _process_task(p_tasks[i]);
  194. }
  195. p_lock.temp_relock();
  196. return;
  197. }
  198. while (runlevel == RUNLEVEL_EXIT_LANGUAGES) {
  199. control_cond_var.wait(p_lock);
  200. }
  201. uint32_t to_process = 0;
  202. uint32_t to_promote = 0;
  203. ThreadData *caller_pool_thread = thread_ids.has(Thread::get_caller_id()) ? &threads[thread_ids[Thread::get_caller_id()]] : nullptr;
  204. for (uint32_t i = 0; i < p_count; i++) {
  205. p_tasks[i]->low_priority = !p_high_priority;
  206. if (p_high_priority || low_priority_threads_used < max_low_priority_threads) {
  207. task_queue.add_last(&p_tasks[i]->task_elem);
  208. if (!p_high_priority) {
  209. low_priority_threads_used++;
  210. }
  211. to_process++;
  212. } else {
  213. // Too many threads using low priority, must go to queue.
  214. low_priority_task_queue.add_last(&p_tasks[i]->task_elem);
  215. to_promote++;
  216. }
  217. }
  218. _notify_threads(caller_pool_thread, to_process, to_promote);
  219. }
  220. void WorkerThreadPool::_notify_threads(const ThreadData *p_current_thread_data, uint32_t p_process_count, uint32_t p_promote_count) {
  221. uint32_t to_process = p_process_count;
  222. uint32_t to_promote = p_promote_count;
  223. // This is where which threads are awaken is decided according to the workload.
  224. // Threads that will anyway have a chance to check the situation and process/promote tasks
  225. // are excluded from being notified. Others will be tried anyway to try to distribute load.
  226. // The current thread, if is a pool thread, is also excluded depending on the promoting/processing
  227. // needs because it will anyway loop again. However, it will contribute to decreasing the count,
  228. // which helps reducing sync traffic.
  229. uint32_t thread_count = threads.size();
  230. // First round:
  231. // 1. For processing: notify threads that are not running tasks, to keep the stacks as shallow as possible.
  232. // 2. For promoting: since it's exclusive with processing, we fin threads able to promote low-prio tasks now.
  233. for (uint32_t i = 0;
  234. i < thread_count && (to_process || to_promote);
  235. i++, notify_index = (notify_index + 1) % thread_count) {
  236. ThreadData &th = threads[notify_index];
  237. if (th.signaled) {
  238. continue;
  239. }
  240. if (th.current_task) {
  241. // Good thread for promoting low-prio?
  242. if (to_promote && th.awaited_task && th.current_task->low_priority) {
  243. if (likely(&th != p_current_thread_data)) {
  244. th.cond_var.notify_one();
  245. }
  246. th.signaled = true;
  247. to_promote--;
  248. }
  249. } else {
  250. if (to_process) {
  251. if (likely(&th != p_current_thread_data)) {
  252. th.cond_var.notify_one();
  253. }
  254. th.signaled = true;
  255. to_process--;
  256. }
  257. }
  258. }
  259. // Second round:
  260. // For processing: if the first round wasn't enough, let's try now with threads processing tasks but currently awaiting.
  261. for (uint32_t i = 0;
  262. i < thread_count && to_process;
  263. i++, notify_index = (notify_index + 1) % thread_count) {
  264. ThreadData &th = threads[notify_index];
  265. if (th.signaled) {
  266. continue;
  267. }
  268. if (th.awaited_task) {
  269. if (likely(&th != p_current_thread_data)) {
  270. th.cond_var.notify_one();
  271. }
  272. th.signaled = true;
  273. to_process--;
  274. }
  275. }
  276. }
  277. bool WorkerThreadPool::_try_promote_low_priority_task() {
  278. if (low_priority_task_queue.first()) {
  279. Task *low_prio_task = low_priority_task_queue.first()->self();
  280. low_priority_task_queue.remove(low_priority_task_queue.first());
  281. task_queue.add_last(&low_prio_task->task_elem);
  282. low_priority_threads_used++;
  283. return true;
  284. } else {
  285. return false;
  286. }
  287. }
  288. WorkerThreadPool::TaskID WorkerThreadPool::add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority, const String &p_description) {
  289. return _add_task(Callable(), p_func, p_userdata, nullptr, p_high_priority, p_description);
  290. }
  291. WorkerThreadPool::TaskID WorkerThreadPool::_add_task(const Callable &p_callable, void (*p_func)(void *), void *p_userdata, BaseTemplateUserdata *p_template_userdata, bool p_high_priority, const String &p_description) {
  292. MutexLock<BinaryMutex> lock(task_mutex);
  293. // Get a free task
  294. Task *task = task_allocator.alloc();
  295. TaskID id = last_task++;
  296. task->self = id;
  297. task->callable = p_callable;
  298. task->native_func = p_func;
  299. task->native_func_userdata = p_userdata;
  300. task->description = p_description;
  301. task->template_userdata = p_template_userdata;
  302. tasks.insert(id, task);
  303. _post_tasks(&task, 1, p_high_priority, lock);
  304. return id;
  305. }
  306. WorkerThreadPool::TaskID WorkerThreadPool::add_task(const Callable &p_action, bool p_high_priority, const String &p_description) {
  307. return _add_task(p_action, nullptr, nullptr, nullptr, p_high_priority, p_description);
  308. }
  309. bool WorkerThreadPool::is_task_completed(TaskID p_task_id) const {
  310. MutexLock task_lock(task_mutex);
  311. const Task *const *taskp = tasks.getptr(p_task_id);
  312. if (!taskp) {
  313. ERR_FAIL_V_MSG(false, "Invalid Task ID"); // Invalid task
  314. }
  315. return (*taskp)->completed;
  316. }
  317. Error WorkerThreadPool::wait_for_task_completion(TaskID p_task_id) {
  318. task_mutex.lock();
  319. Task **taskp = tasks.getptr(p_task_id);
  320. if (!taskp) {
  321. task_mutex.unlock();
  322. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Invalid Task ID"); // Invalid task
  323. }
  324. Task *task = *taskp;
  325. if (task->completed) {
  326. if (task->waiting_pool == 0 && task->waiting_user == 0) {
  327. tasks.erase(p_task_id);
  328. task_allocator.free(task);
  329. }
  330. task_mutex.unlock();
  331. return OK;
  332. }
  333. ThreadData *caller_pool_thread = thread_ids.has(Thread::get_caller_id()) ? &threads[thread_ids[Thread::get_caller_id()]] : nullptr;
  334. if (caller_pool_thread && p_task_id <= caller_pool_thread->current_task->self) {
  335. // Deadlock prevention:
  336. // When a pool thread wants to wait for an older task, the following situations can happen:
  337. // 1. Awaited task is deep in the stack of the awaiter.
  338. // 2. A group of awaiter threads end up depending on some tasks buried in the stack
  339. // of their worker threads in such a way that progress can't be made.
  340. // Both would entail a deadlock. Some may be handled here in the WorkerThreadPool
  341. // with some extra logic and bookkeeping. However, there would still be unavoidable
  342. // cases of deadlock because of the way waiting threads process outstanding tasks.
  343. // Taking into account there's no feasible solution for every possible case
  344. // with the current design, we just simply reject attempts to await on older tasks,
  345. // with a specific error code that signals the situation so the caller can handle it.
  346. task_mutex.unlock();
  347. return ERR_BUSY;
  348. }
  349. if (caller_pool_thread) {
  350. task->waiting_pool++;
  351. } else {
  352. task->waiting_user++;
  353. }
  354. if (caller_pool_thread) {
  355. task_mutex.unlock();
  356. _wait_collaboratively(caller_pool_thread, task);
  357. task_mutex.lock();
  358. task->waiting_pool--;
  359. if (task->waiting_pool == 0 && task->waiting_user == 0) {
  360. tasks.erase(p_task_id);
  361. task_allocator.free(task);
  362. }
  363. } else {
  364. task_mutex.unlock();
  365. task->done_semaphore.wait();
  366. task_mutex.lock();
  367. task->waiting_user--;
  368. if (task->waiting_pool == 0 && task->waiting_user == 0) {
  369. tasks.erase(p_task_id);
  370. task_allocator.free(task);
  371. }
  372. }
  373. task_mutex.unlock();
  374. return OK;
  375. }
  376. void WorkerThreadPool::_lock_unlockable_mutexes() {
  377. #ifdef THREADS_ENABLED
  378. for (uint32_t i = 0; i < MAX_UNLOCKABLE_LOCKS; i++) {
  379. if (unlockable_locks[i].ulock) {
  380. unlockable_locks[i].ulock->lock();
  381. }
  382. }
  383. #endif
  384. }
  385. void WorkerThreadPool::_unlock_unlockable_mutexes() {
  386. #ifdef THREADS_ENABLED
  387. for (uint32_t i = 0; i < MAX_UNLOCKABLE_LOCKS; i++) {
  388. if (unlockable_locks[i].ulock) {
  389. unlockable_locks[i].ulock->unlock();
  390. }
  391. }
  392. #endif
  393. }
  394. void WorkerThreadPool::_wait_collaboratively(ThreadData *p_caller_pool_thread, Task *p_task) {
  395. // Keep processing tasks until the condition to stop waiting is met.
  396. while (true) {
  397. Task *task_to_process = nullptr;
  398. bool relock_unlockables = false;
  399. {
  400. MutexLock lock(task_mutex);
  401. bool was_signaled = p_caller_pool_thread->signaled;
  402. p_caller_pool_thread->signaled = false;
  403. bool exit = _handle_runlevel(p_caller_pool_thread, lock);
  404. if (unlikely(exit)) {
  405. break;
  406. }
  407. bool wait_is_over = false;
  408. if (unlikely(p_task == ThreadData::YIELDING)) {
  409. if (p_caller_pool_thread->yield_is_over) {
  410. p_caller_pool_thread->yield_is_over = false;
  411. wait_is_over = true;
  412. }
  413. } else {
  414. if (p_task->completed) {
  415. wait_is_over = true;
  416. }
  417. }
  418. if (wait_is_over) {
  419. if (was_signaled) {
  420. // This thread was awaken for some additional reason, but it's about to exit.
  421. // Let's find out what may be pending and forward the requests.
  422. uint32_t to_process = task_queue.first() ? 1 : 0;
  423. uint32_t to_promote = p_caller_pool_thread->current_task->low_priority && low_priority_task_queue.first() ? 1 : 0;
  424. if (to_process || to_promote) {
  425. // This thread must be left alone since it won't loop again.
  426. p_caller_pool_thread->signaled = true;
  427. _notify_threads(p_caller_pool_thread, to_process, to_promote);
  428. }
  429. }
  430. break;
  431. }
  432. if (p_caller_pool_thread->current_task->low_priority && low_priority_task_queue.first()) {
  433. if (_try_promote_low_priority_task()) {
  434. _notify_threads(p_caller_pool_thread, 1, 0);
  435. }
  436. }
  437. if (p_caller_pool_thread->pool->task_queue.first()) {
  438. task_to_process = task_queue.first()->self();
  439. task_queue.remove(task_queue.first());
  440. }
  441. if (!task_to_process) {
  442. p_caller_pool_thread->awaited_task = p_task;
  443. if (this == singleton) {
  444. _unlock_unlockable_mutexes();
  445. }
  446. relock_unlockables = true;
  447. p_caller_pool_thread->cond_var.wait(lock);
  448. p_caller_pool_thread->awaited_task = nullptr;
  449. }
  450. }
  451. if (relock_unlockables && this == singleton) {
  452. _lock_unlockable_mutexes();
  453. }
  454. if (task_to_process) {
  455. _process_task(task_to_process);
  456. }
  457. }
  458. }
  459. void WorkerThreadPool::_switch_runlevel(Runlevel p_runlevel) {
  460. DEV_ASSERT(p_runlevel > runlevel);
  461. runlevel = p_runlevel;
  462. memset(&runlevel_data, 0, sizeof(runlevel_data));
  463. for (uint32_t i = 0; i < threads.size(); i++) {
  464. threads[i].cond_var.notify_one();
  465. threads[i].signaled = true;
  466. }
  467. control_cond_var.notify_all();
  468. }
  469. // Returns whether threads have to exit. This may perform the check about handling needed.
  470. bool WorkerThreadPool::_handle_runlevel(ThreadData *p_thread_data, MutexLock<BinaryMutex> &p_lock) {
  471. bool exit = false;
  472. switch (runlevel) {
  473. case RUNLEVEL_NORMAL: {
  474. } break;
  475. case RUNLEVEL_PRE_EXIT_LANGUAGES: {
  476. if (!p_thread_data->pre_exited_languages) {
  477. if (!task_queue.first() && !low_priority_task_queue.first()) {
  478. p_thread_data->pre_exited_languages = true;
  479. runlevel_data.pre_exit_languages.num_idle_threads++;
  480. control_cond_var.notify_all();
  481. }
  482. }
  483. } break;
  484. case RUNLEVEL_EXIT_LANGUAGES: {
  485. if (!p_thread_data->exited_languages) {
  486. p_lock.temp_unlock();
  487. ScriptServer::thread_exit();
  488. p_lock.temp_relock();
  489. p_thread_data->exited_languages = true;
  490. runlevel_data.exit_languages.num_exited_threads++;
  491. control_cond_var.notify_all();
  492. }
  493. } break;
  494. case RUNLEVEL_EXIT: {
  495. exit = true;
  496. } break;
  497. }
  498. return exit;
  499. }
  500. void WorkerThreadPool::yield() {
  501. int th_index = get_thread_index();
  502. ERR_FAIL_COND_MSG(th_index == -1, "This function can only be called from a worker thread.");
  503. _wait_collaboratively(&threads[th_index], ThreadData::YIELDING);
  504. task_mutex.lock();
  505. if (runlevel < RUNLEVEL_EXIT_LANGUAGES) {
  506. // If this long-lived task started before the scripting server was initialized,
  507. // now is a good time to have scripting languages ready for the current thread.
  508. // Otherwise, such a piece of setup won't happen unless another task has been
  509. // run during the collaborative wait.
  510. task_mutex.unlock();
  511. ScriptServer::thread_enter();
  512. } else {
  513. task_mutex.unlock();
  514. }
  515. }
  516. void WorkerThreadPool::notify_yield_over(TaskID p_task_id) {
  517. MutexLock task_lock(task_mutex);
  518. Task **taskp = tasks.getptr(p_task_id);
  519. if (!taskp) {
  520. ERR_FAIL_MSG("Invalid Task ID.");
  521. }
  522. Task *task = *taskp;
  523. if (task->pool_thread_index == -1) { // Completed or not started yet.
  524. if (!task->completed) {
  525. // This avoids a race condition where a task is created and yield-over called before it's processed.
  526. task->pending_notify_yield_over = true;
  527. }
  528. return;
  529. }
  530. ThreadData &td = threads[task->pool_thread_index];
  531. td.yield_is_over = true;
  532. td.signaled = true;
  533. td.cond_var.notify_one();
  534. }
  535. WorkerThreadPool::GroupID WorkerThreadPool::_add_group_task(const Callable &p_callable, void (*p_func)(void *, uint32_t), void *p_userdata, BaseTemplateUserdata *p_template_userdata, int p_elements, int p_tasks, bool p_high_priority, const String &p_description) {
  536. ERR_FAIL_COND_V(p_elements < 0, INVALID_TASK_ID);
  537. if (p_tasks < 0) {
  538. p_tasks = MAX(1u, threads.size());
  539. }
  540. MutexLock<BinaryMutex> lock(task_mutex);
  541. Group *group = group_allocator.alloc();
  542. GroupID id = last_task++;
  543. group->max = p_elements;
  544. group->self = id;
  545. Task **tasks_posted = nullptr;
  546. if (p_elements == 0) {
  547. // Should really not call it with zero Elements, but at least it should work.
  548. group->completed.set_to(true);
  549. group->done_semaphore.post();
  550. group->tasks_used = 0;
  551. p_tasks = 0;
  552. if (p_template_userdata) {
  553. memdelete(p_template_userdata);
  554. }
  555. } else {
  556. group->tasks_used = p_tasks;
  557. tasks_posted = (Task **)alloca(sizeof(Task *) * p_tasks);
  558. for (int i = 0; i < p_tasks; i++) {
  559. Task *task = task_allocator.alloc();
  560. task->native_group_func = p_func;
  561. task->native_func_userdata = p_userdata;
  562. task->description = p_description;
  563. task->group = group;
  564. task->callable = p_callable;
  565. task->template_userdata = p_template_userdata;
  566. tasks_posted[i] = task;
  567. // No task ID is used.
  568. }
  569. }
  570. groups[id] = group;
  571. _post_tasks(tasks_posted, p_tasks, p_high_priority, lock);
  572. return id;
  573. }
  574. WorkerThreadPool::GroupID WorkerThreadPool::add_native_group_task(void (*p_func)(void *, uint32_t), void *p_userdata, int p_elements, int p_tasks, bool p_high_priority, const String &p_description) {
  575. return _add_group_task(Callable(), p_func, p_userdata, nullptr, p_elements, p_tasks, p_high_priority, p_description);
  576. }
  577. WorkerThreadPool::GroupID WorkerThreadPool::add_group_task(const Callable &p_action, int p_elements, int p_tasks, bool p_high_priority, const String &p_description) {
  578. return _add_group_task(p_action, nullptr, nullptr, nullptr, p_elements, p_tasks, p_high_priority, p_description);
  579. }
  580. uint32_t WorkerThreadPool::get_group_processed_element_count(GroupID p_group) const {
  581. MutexLock task_lock(task_mutex);
  582. const Group *const *groupp = groups.getptr(p_group);
  583. if (!groupp) {
  584. ERR_FAIL_V_MSG(0, "Invalid Group ID");
  585. }
  586. return (*groupp)->completed_index.get();
  587. }
  588. bool WorkerThreadPool::is_group_task_completed(GroupID p_group) const {
  589. MutexLock task_lock(task_mutex);
  590. const Group *const *groupp = groups.getptr(p_group);
  591. if (!groupp) {
  592. ERR_FAIL_V_MSG(false, "Invalid Group ID");
  593. }
  594. return (*groupp)->completed.is_set();
  595. }
  596. void WorkerThreadPool::wait_for_group_task_completion(GroupID p_group) {
  597. #ifdef THREADS_ENABLED
  598. task_mutex.lock();
  599. Group **groupp = groups.getptr(p_group);
  600. task_mutex.unlock();
  601. if (!groupp) {
  602. ERR_FAIL_MSG("Invalid Group ID.");
  603. }
  604. {
  605. Group *group = *groupp;
  606. if (this == singleton) {
  607. _unlock_unlockable_mutexes();
  608. }
  609. group->done_semaphore.wait();
  610. if (this == singleton) {
  611. _lock_unlockable_mutexes();
  612. }
  613. uint32_t max_users = group->tasks_used + 1; // Add 1 because the thread waiting for it is also user. Read before to avoid another thread freeing task after increment.
  614. uint32_t finished_users = group->finished.increment(); // fetch happens before inc, so increment later.
  615. if (finished_users == max_users) {
  616. // All tasks using this group are gone (finished before the group), so clear the group too.
  617. MutexLock task_lock(task_mutex);
  618. group_allocator.free(group);
  619. }
  620. }
  621. MutexLock task_lock(task_mutex); // This mutex is needed when Physics 2D and/or 3D is selected to run on a separate thread.
  622. groups.erase(p_group);
  623. #endif
  624. }
  625. int WorkerThreadPool::get_thread_index() const {
  626. Thread::ID tid = Thread::get_caller_id();
  627. return thread_ids.has(tid) ? thread_ids[tid] : -1;
  628. }
  629. WorkerThreadPool::TaskID WorkerThreadPool::get_caller_task_id() const {
  630. int th_index = get_thread_index();
  631. if (th_index != -1 && threads[th_index].current_task) {
  632. return threads[th_index].current_task->self;
  633. } else {
  634. return INVALID_TASK_ID;
  635. }
  636. }
  637. WorkerThreadPool::GroupID WorkerThreadPool::get_caller_group_id() const {
  638. int th_index = get_thread_index();
  639. if (th_index != -1 && threads[th_index].current_task && threads[th_index].current_task->group) {
  640. return threads[th_index].current_task->group->self;
  641. } else {
  642. return INVALID_TASK_ID;
  643. }
  644. }
  645. #ifdef THREADS_ENABLED
  646. uint32_t WorkerThreadPool::_thread_enter_unlock_allowance_zone(THREADING_NAMESPACE::unique_lock<THREADING_NAMESPACE::mutex> &p_ulock) {
  647. for (uint32_t i = 0; i < MAX_UNLOCKABLE_LOCKS; i++) {
  648. DEV_ASSERT((bool)unlockable_locks[i].ulock == (bool)unlockable_locks[i].rc);
  649. if (unlockable_locks[i].ulock == &p_ulock) {
  650. // Already registered in the current thread.
  651. unlockable_locks[i].rc++;
  652. return i;
  653. } else if (!unlockable_locks[i].ulock) {
  654. unlockable_locks[i].ulock = &p_ulock;
  655. unlockable_locks[i].rc = 1;
  656. return i;
  657. }
  658. }
  659. ERR_FAIL_V_MSG(UINT32_MAX, "No more unlockable lock slots available. Engine bug.");
  660. }
  661. void WorkerThreadPool::thread_exit_unlock_allowance_zone(uint32_t p_zone_id) {
  662. DEV_ASSERT(unlockable_locks[p_zone_id].ulock && unlockable_locks[p_zone_id].rc);
  663. unlockable_locks[p_zone_id].rc--;
  664. if (unlockable_locks[p_zone_id].rc == 0) {
  665. unlockable_locks[p_zone_id].ulock = nullptr;
  666. }
  667. }
  668. #endif
  669. void WorkerThreadPool::init(int p_thread_count, float p_low_priority_task_ratio) {
  670. ERR_FAIL_COND(threads.size() > 0);
  671. runlevel = RUNLEVEL_NORMAL;
  672. if (p_thread_count < 0) {
  673. p_thread_count = OS::get_singleton()->get_default_thread_pool_size();
  674. }
  675. max_low_priority_threads = CLAMP(p_thread_count * p_low_priority_task_ratio, 1, p_thread_count - 1);
  676. print_verbose(vformat("WorkerThreadPool: %d threads, %d max low-priority.", p_thread_count, max_low_priority_threads));
  677. threads.resize(p_thread_count);
  678. Thread::Settings settings;
  679. #ifdef __APPLE__
  680. // The default stack size for new threads on Apple platforms is 512KiB.
  681. // This is insufficient when using a library like SPIRV-Cross,
  682. // which can generate deep stacks and result in a stack overflow.
  683. #ifdef DEV_ENABLED
  684. // Debug builds need an even larger stack size.
  685. settings.stack_size = 2 * 1024 * 1024; // 2 MiB
  686. #else
  687. settings.stack_size = 1 * 1024 * 1024; // 1 MiB
  688. #endif
  689. #endif
  690. for (uint32_t i = 0; i < threads.size(); i++) {
  691. threads[i].index = i;
  692. threads[i].pool = this;
  693. threads[i].thread.start(&WorkerThreadPool::_thread_function, &threads[i], settings);
  694. thread_ids.insert(threads[i].thread.get_id(), i);
  695. }
  696. }
  697. void WorkerThreadPool::exit_languages_threads() {
  698. if (threads.is_empty()) {
  699. return;
  700. }
  701. MutexLock lock(task_mutex);
  702. // Wait until all threads are idle.
  703. _switch_runlevel(RUNLEVEL_PRE_EXIT_LANGUAGES);
  704. while (runlevel_data.pre_exit_languages.num_idle_threads != threads.size()) {
  705. control_cond_var.wait(lock);
  706. }
  707. // Wait until all threads have detached from scripting languages.
  708. _switch_runlevel(RUNLEVEL_EXIT_LANGUAGES);
  709. while (runlevel_data.exit_languages.num_exited_threads != threads.size()) {
  710. control_cond_var.wait(lock);
  711. }
  712. }
  713. void WorkerThreadPool::finish() {
  714. if (threads.is_empty()) {
  715. return;
  716. }
  717. {
  718. MutexLock lock(task_mutex);
  719. SelfList<Task> *E = low_priority_task_queue.first();
  720. while (E) {
  721. print_error("Task waiting was never re-claimed: " + E->self()->description);
  722. E = E->next();
  723. }
  724. _switch_runlevel(RUNLEVEL_EXIT);
  725. }
  726. for (ThreadData &data : threads) {
  727. data.thread.wait_to_finish();
  728. }
  729. {
  730. MutexLock lock(task_mutex);
  731. for (KeyValue<TaskID, Task *> &E : tasks) {
  732. task_allocator.free(E.value);
  733. }
  734. }
  735. threads.clear();
  736. }
  737. void WorkerThreadPool::_bind_methods() {
  738. ClassDB::bind_method(D_METHOD("add_task", "action", "high_priority", "description"), &WorkerThreadPool::add_task, DEFVAL(false), DEFVAL(String()));
  739. ClassDB::bind_method(D_METHOD("is_task_completed", "task_id"), &WorkerThreadPool::is_task_completed);
  740. ClassDB::bind_method(D_METHOD("wait_for_task_completion", "task_id"), &WorkerThreadPool::wait_for_task_completion);
  741. ClassDB::bind_method(D_METHOD("get_caller_task_id"), &WorkerThreadPool::get_caller_task_id);
  742. ClassDB::bind_method(D_METHOD("add_group_task", "action", "elements", "tasks_needed", "high_priority", "description"), &WorkerThreadPool::add_group_task, DEFVAL(-1), DEFVAL(false), DEFVAL(String()));
  743. ClassDB::bind_method(D_METHOD("is_group_task_completed", "group_id"), &WorkerThreadPool::is_group_task_completed);
  744. ClassDB::bind_method(D_METHOD("get_group_processed_element_count", "group_id"), &WorkerThreadPool::get_group_processed_element_count);
  745. ClassDB::bind_method(D_METHOD("wait_for_group_task_completion", "group_id"), &WorkerThreadPool::wait_for_group_task_completion);
  746. ClassDB::bind_method(D_METHOD("get_caller_group_id"), &WorkerThreadPool::get_caller_group_id);
  747. }
  748. WorkerThreadPool *WorkerThreadPool::get_named_pool(const StringName &p_name) {
  749. WorkerThreadPool **pool_ptr = named_pools.getptr(p_name);
  750. if (pool_ptr) {
  751. return *pool_ptr;
  752. } else {
  753. WorkerThreadPool *pool = memnew(WorkerThreadPool(false));
  754. pool->init();
  755. named_pools[p_name] = pool;
  756. return pool;
  757. }
  758. }
  759. WorkerThreadPool::WorkerThreadPool(bool p_singleton) {
  760. if (p_singleton) {
  761. singleton = this;
  762. }
  763. }
  764. WorkerThreadPool::~WorkerThreadPool() {
  765. finish();
  766. if (this == singleton) {
  767. singleton = nullptr;
  768. for (KeyValue<StringName, WorkerThreadPool *> &E : named_pools) {
  769. E.value->finish();
  770. memdelete(E.value);
  771. }
  772. named_pools.clear();
  773. }
  774. }