worker_thread_pool.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. while (true) {
  157. Task *task_to_process = nullptr;
  158. {
  159. // Create the lock outside the inner loop so it isn't needlessly unlocked and relocked
  160. // when no task was found to process, and the loop is re-entered.
  161. MutexLock lock(thread_data->pool->task_mutex);
  162. while (true) {
  163. bool exit = thread_data->pool->_handle_runlevel(thread_data, lock);
  164. if (unlikely(exit)) {
  165. return;
  166. }
  167. thread_data->signaled = false;
  168. if (!thread_data->pool->task_queue.first()) {
  169. // There wasn't a task available yet.
  170. // Let's wait for the next notification, then recheck.
  171. thread_data->cond_var.wait(lock);
  172. continue;
  173. }
  174. // Got a task to process! Remove it from the queue, then break into the task handling section.
  175. task_to_process = thread_data->pool->task_queue.first()->self();
  176. thread_data->pool->task_queue.remove(thread_data->pool->task_queue.first());
  177. break;
  178. }
  179. }
  180. DEV_ASSERT(task_to_process);
  181. thread_data->pool->_process_task(task_to_process);
  182. }
  183. }
  184. void WorkerThreadPool::_post_tasks(Task **p_tasks, uint32_t p_count, bool p_high_priority, MutexLock<BinaryMutex> &p_lock) {
  185. // Fall back to processing on the calling thread if there are no worker threads.
  186. // Separated into its own variable to make it easier to extend this logic
  187. // in custom builds.
  188. bool process_on_calling_thread = threads.is_empty();
  189. if (process_on_calling_thread) {
  190. p_lock.temp_unlock();
  191. for (uint32_t i = 0; i < p_count; i++) {
  192. _process_task(p_tasks[i]);
  193. }
  194. p_lock.temp_relock();
  195. return;
  196. }
  197. while (runlevel == RUNLEVEL_EXIT_LANGUAGES) {
  198. control_cond_var.wait(p_lock);
  199. }
  200. uint32_t to_process = 0;
  201. uint32_t to_promote = 0;
  202. ThreadData *caller_pool_thread = thread_ids.has(Thread::get_caller_id()) ? &threads[thread_ids[Thread::get_caller_id()]] : nullptr;
  203. for (uint32_t i = 0; i < p_count; i++) {
  204. p_tasks[i]->low_priority = !p_high_priority;
  205. if (p_high_priority || low_priority_threads_used < max_low_priority_threads) {
  206. task_queue.add_last(&p_tasks[i]->task_elem);
  207. if (!p_high_priority) {
  208. low_priority_threads_used++;
  209. }
  210. to_process++;
  211. } else {
  212. // Too many threads using low priority, must go to queue.
  213. low_priority_task_queue.add_last(&p_tasks[i]->task_elem);
  214. to_promote++;
  215. }
  216. }
  217. _notify_threads(caller_pool_thread, to_process, to_promote);
  218. }
  219. void WorkerThreadPool::_notify_threads(const ThreadData *p_current_thread_data, uint32_t p_process_count, uint32_t p_promote_count) {
  220. uint32_t to_process = p_process_count;
  221. uint32_t to_promote = p_promote_count;
  222. // This is where which threads are awaken is decided according to the workload.
  223. // Threads that will anyway have a chance to check the situation and process/promote tasks
  224. // are excluded from being notified. Others will be tried anyway to try to distribute load.
  225. // The current thread, if is a pool thread, is also excluded depending on the promoting/processing
  226. // needs because it will anyway loop again. However, it will contribute to decreasing the count,
  227. // which helps reducing sync traffic.
  228. uint32_t thread_count = threads.size();
  229. // First round:
  230. // 1. For processing: notify threads that are not running tasks, to keep the stacks as shallow as possible.
  231. // 2. For promoting: since it's exclusive with processing, we fin threads able to promote low-prio tasks now.
  232. for (uint32_t i = 0;
  233. i < thread_count && (to_process || to_promote);
  234. i++, notify_index = (notify_index + 1) % thread_count) {
  235. ThreadData &th = threads[notify_index];
  236. if (th.signaled) {
  237. continue;
  238. }
  239. if (th.current_task) {
  240. // Good thread for promoting low-prio?
  241. if (to_promote && th.awaited_task && th.current_task->low_priority) {
  242. if (likely(&th != p_current_thread_data)) {
  243. th.cond_var.notify_one();
  244. }
  245. th.signaled = true;
  246. to_promote--;
  247. }
  248. } else {
  249. if (to_process) {
  250. if (likely(&th != p_current_thread_data)) {
  251. th.cond_var.notify_one();
  252. }
  253. th.signaled = true;
  254. to_process--;
  255. }
  256. }
  257. }
  258. // Second round:
  259. // For processing: if the first round wasn't enough, let's try now with threads processing tasks but currently awaiting.
  260. for (uint32_t i = 0;
  261. i < thread_count && to_process;
  262. i++, notify_index = (notify_index + 1) % thread_count) {
  263. ThreadData &th = threads[notify_index];
  264. if (th.signaled) {
  265. continue;
  266. }
  267. if (th.awaited_task) {
  268. if (likely(&th != p_current_thread_data)) {
  269. th.cond_var.notify_one();
  270. }
  271. th.signaled = true;
  272. to_process--;
  273. }
  274. }
  275. }
  276. bool WorkerThreadPool::_try_promote_low_priority_task() {
  277. if (low_priority_task_queue.first()) {
  278. Task *low_prio_task = low_priority_task_queue.first()->self();
  279. low_priority_task_queue.remove(low_priority_task_queue.first());
  280. task_queue.add_last(&low_prio_task->task_elem);
  281. low_priority_threads_used++;
  282. return true;
  283. } else {
  284. return false;
  285. }
  286. }
  287. WorkerThreadPool::TaskID WorkerThreadPool::add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority, const String &p_description) {
  288. return _add_task(Callable(), p_func, p_userdata, nullptr, p_high_priority, p_description);
  289. }
  290. 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) {
  291. MutexLock<BinaryMutex> lock(task_mutex);
  292. // Get a free task
  293. Task *task = task_allocator.alloc();
  294. TaskID id = last_task++;
  295. task->self = id;
  296. task->callable = p_callable;
  297. task->native_func = p_func;
  298. task->native_func_userdata = p_userdata;
  299. task->description = p_description;
  300. task->template_userdata = p_template_userdata;
  301. tasks.insert(id, task);
  302. _post_tasks(&task, 1, p_high_priority, lock);
  303. return id;
  304. }
  305. WorkerThreadPool::TaskID WorkerThreadPool::add_task(const Callable &p_action, bool p_high_priority, const String &p_description) {
  306. return _add_task(p_action, nullptr, nullptr, nullptr, p_high_priority, p_description);
  307. }
  308. bool WorkerThreadPool::is_task_completed(TaskID p_task_id) const {
  309. MutexLock task_lock(task_mutex);
  310. const Task *const *taskp = tasks.getptr(p_task_id);
  311. if (!taskp) {
  312. ERR_FAIL_V_MSG(false, "Invalid Task ID"); // Invalid task
  313. }
  314. return (*taskp)->completed;
  315. }
  316. Error WorkerThreadPool::wait_for_task_completion(TaskID p_task_id) {
  317. task_mutex.lock();
  318. Task **taskp = tasks.getptr(p_task_id);
  319. if (!taskp) {
  320. task_mutex.unlock();
  321. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Invalid Task ID"); // Invalid task
  322. }
  323. Task *task = *taskp;
  324. if (task->completed) {
  325. if (task->waiting_pool == 0 && task->waiting_user == 0) {
  326. tasks.erase(p_task_id);
  327. task_allocator.free(task);
  328. }
  329. task_mutex.unlock();
  330. return OK;
  331. }
  332. ThreadData *caller_pool_thread = thread_ids.has(Thread::get_caller_id()) ? &threads[thread_ids[Thread::get_caller_id()]] : nullptr;
  333. if (caller_pool_thread && p_task_id <= caller_pool_thread->current_task->self) {
  334. // Deadlock prevention:
  335. // When a pool thread wants to wait for an older task, the following situations can happen:
  336. // 1. Awaited task is deep in the stack of the awaiter.
  337. // 2. A group of awaiter threads end up depending on some tasks buried in the stack
  338. // of their worker threads in such a way that progress can't be made.
  339. // Both would entail a deadlock. Some may be handled here in the WorkerThreadPool
  340. // with some extra logic and bookkeeping. However, there would still be unavoidable
  341. // cases of deadlock because of the way waiting threads process outstanding tasks.
  342. // Taking into account there's no feasible solution for every possible case
  343. // with the current design, we just simply reject attempts to await on older tasks,
  344. // with a specific error code that signals the situation so the caller can handle it.
  345. task_mutex.unlock();
  346. return ERR_BUSY;
  347. }
  348. if (caller_pool_thread) {
  349. task->waiting_pool++;
  350. } else {
  351. task->waiting_user++;
  352. }
  353. if (caller_pool_thread) {
  354. task_mutex.unlock();
  355. _wait_collaboratively(caller_pool_thread, task);
  356. task_mutex.lock();
  357. task->waiting_pool--;
  358. if (task->waiting_pool == 0 && task->waiting_user == 0) {
  359. tasks.erase(p_task_id);
  360. task_allocator.free(task);
  361. }
  362. } else {
  363. task_mutex.unlock();
  364. task->done_semaphore.wait();
  365. task_mutex.lock();
  366. task->waiting_user--;
  367. if (task->waiting_pool == 0 && task->waiting_user == 0) {
  368. tasks.erase(p_task_id);
  369. task_allocator.free(task);
  370. }
  371. }
  372. task_mutex.unlock();
  373. return OK;
  374. }
  375. void WorkerThreadPool::_lock_unlockable_mutexes() {
  376. #ifdef THREADS_ENABLED
  377. for (uint32_t i = 0; i < MAX_UNLOCKABLE_LOCKS; i++) {
  378. if (unlockable_locks[i].ulock) {
  379. unlockable_locks[i].ulock->lock();
  380. }
  381. }
  382. #endif
  383. }
  384. void WorkerThreadPool::_unlock_unlockable_mutexes() {
  385. #ifdef THREADS_ENABLED
  386. for (uint32_t i = 0; i < MAX_UNLOCKABLE_LOCKS; i++) {
  387. if (unlockable_locks[i].ulock) {
  388. unlockable_locks[i].ulock->unlock();
  389. }
  390. }
  391. #endif
  392. }
  393. void WorkerThreadPool::_wait_collaboratively(ThreadData *p_caller_pool_thread, Task *p_task) {
  394. // Keep processing tasks until the condition to stop waiting is met.
  395. while (true) {
  396. Task *task_to_process = nullptr;
  397. bool relock_unlockables = false;
  398. {
  399. MutexLock lock(task_mutex);
  400. bool was_signaled = p_caller_pool_thread->signaled;
  401. p_caller_pool_thread->signaled = false;
  402. bool exit = _handle_runlevel(p_caller_pool_thread, lock);
  403. if (unlikely(exit)) {
  404. break;
  405. }
  406. bool wait_is_over = false;
  407. if (unlikely(p_task == ThreadData::YIELDING)) {
  408. if (p_caller_pool_thread->yield_is_over) {
  409. p_caller_pool_thread->yield_is_over = false;
  410. wait_is_over = true;
  411. }
  412. } else {
  413. if (p_task->completed) {
  414. wait_is_over = true;
  415. }
  416. }
  417. if (wait_is_over) {
  418. if (was_signaled) {
  419. // This thread was awaken for some additional reason, but it's about to exit.
  420. // Let's find out what may be pending and forward the requests.
  421. uint32_t to_process = task_queue.first() ? 1 : 0;
  422. uint32_t to_promote = p_caller_pool_thread->current_task->low_priority && low_priority_task_queue.first() ? 1 : 0;
  423. if (to_process || to_promote) {
  424. // This thread must be left alone since it won't loop again.
  425. p_caller_pool_thread->signaled = true;
  426. _notify_threads(p_caller_pool_thread, to_process, to_promote);
  427. }
  428. }
  429. break;
  430. }
  431. if (p_caller_pool_thread->current_task->low_priority && low_priority_task_queue.first()) {
  432. if (_try_promote_low_priority_task()) {
  433. _notify_threads(p_caller_pool_thread, 1, 0);
  434. }
  435. }
  436. if (p_caller_pool_thread->pool->task_queue.first()) {
  437. task_to_process = task_queue.first()->self();
  438. task_queue.remove(task_queue.first());
  439. }
  440. if (!task_to_process) {
  441. p_caller_pool_thread->awaited_task = p_task;
  442. if (this == singleton) {
  443. _unlock_unlockable_mutexes();
  444. }
  445. relock_unlockables = true;
  446. p_caller_pool_thread->cond_var.wait(lock);
  447. p_caller_pool_thread->awaited_task = nullptr;
  448. }
  449. }
  450. if (relock_unlockables && this == singleton) {
  451. _lock_unlockable_mutexes();
  452. }
  453. if (task_to_process) {
  454. _process_task(task_to_process);
  455. }
  456. }
  457. }
  458. void WorkerThreadPool::_switch_runlevel(Runlevel p_runlevel) {
  459. DEV_ASSERT(p_runlevel > runlevel);
  460. runlevel = p_runlevel;
  461. memset(&runlevel_data, 0, sizeof(runlevel_data));
  462. for (uint32_t i = 0; i < threads.size(); i++) {
  463. threads[i].cond_var.notify_one();
  464. threads[i].signaled = true;
  465. }
  466. control_cond_var.notify_all();
  467. }
  468. // Returns whether threads have to exit. This may perform the check about handling needed.
  469. bool WorkerThreadPool::_handle_runlevel(ThreadData *p_thread_data, MutexLock<BinaryMutex> &p_lock) {
  470. bool exit = false;
  471. switch (runlevel) {
  472. case RUNLEVEL_NORMAL: {
  473. } break;
  474. case RUNLEVEL_PRE_EXIT_LANGUAGES: {
  475. if (!p_thread_data->pre_exited_languages) {
  476. if (!task_queue.first() && !low_priority_task_queue.first()) {
  477. p_thread_data->pre_exited_languages = true;
  478. runlevel_data.pre_exit_languages.num_idle_threads++;
  479. control_cond_var.notify_all();
  480. }
  481. }
  482. } break;
  483. case RUNLEVEL_EXIT_LANGUAGES: {
  484. if (!p_thread_data->exited_languages) {
  485. p_lock.temp_unlock();
  486. ScriptServer::thread_exit();
  487. p_lock.temp_relock();
  488. p_thread_data->exited_languages = true;
  489. runlevel_data.exit_languages.num_exited_threads++;
  490. control_cond_var.notify_all();
  491. }
  492. } break;
  493. case RUNLEVEL_EXIT: {
  494. exit = true;
  495. } break;
  496. }
  497. return exit;
  498. }
  499. void WorkerThreadPool::yield() {
  500. int th_index = get_thread_index();
  501. ERR_FAIL_COND_MSG(th_index == -1, "This function can only be called from a worker thread.");
  502. _wait_collaboratively(&threads[th_index], ThreadData::YIELDING);
  503. task_mutex.lock();
  504. if (runlevel < RUNLEVEL_EXIT_LANGUAGES) {
  505. // If this long-lived task started before the scripting server was initialized,
  506. // now is a good time to have scripting languages ready for the current thread.
  507. // Otherwise, such a piece of setup won't happen unless another task has been
  508. // run during the collaborative wait.
  509. task_mutex.unlock();
  510. ScriptServer::thread_enter();
  511. } else {
  512. task_mutex.unlock();
  513. }
  514. }
  515. void WorkerThreadPool::notify_yield_over(TaskID p_task_id) {
  516. MutexLock task_lock(task_mutex);
  517. Task **taskp = tasks.getptr(p_task_id);
  518. if (!taskp) {
  519. ERR_FAIL_MSG("Invalid Task ID.");
  520. }
  521. Task *task = *taskp;
  522. if (task->pool_thread_index == -1) { // Completed or not started yet.
  523. if (!task->completed) {
  524. // This avoids a race condition where a task is created and yield-over called before it's processed.
  525. task->pending_notify_yield_over = true;
  526. }
  527. return;
  528. }
  529. ThreadData &td = threads[task->pool_thread_index];
  530. td.yield_is_over = true;
  531. td.signaled = true;
  532. td.cond_var.notify_one();
  533. }
  534. 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) {
  535. ERR_FAIL_COND_V(p_elements < 0, INVALID_TASK_ID);
  536. if (p_tasks < 0) {
  537. p_tasks = MAX(1u, threads.size());
  538. }
  539. MutexLock<BinaryMutex> lock(task_mutex);
  540. Group *group = group_allocator.alloc();
  541. GroupID id = last_task++;
  542. group->max = p_elements;
  543. group->self = id;
  544. Task **tasks_posted = nullptr;
  545. if (p_elements == 0) {
  546. // Should really not call it with zero Elements, but at least it should work.
  547. group->completed.set_to(true);
  548. group->done_semaphore.post();
  549. group->tasks_used = 0;
  550. p_tasks = 0;
  551. if (p_template_userdata) {
  552. memdelete(p_template_userdata);
  553. }
  554. } else {
  555. group->tasks_used = p_tasks;
  556. tasks_posted = (Task **)alloca(sizeof(Task *) * p_tasks);
  557. for (int i = 0; i < p_tasks; i++) {
  558. Task *task = task_allocator.alloc();
  559. task->native_group_func = p_func;
  560. task->native_func_userdata = p_userdata;
  561. task->description = p_description;
  562. task->group = group;
  563. task->callable = p_callable;
  564. task->template_userdata = p_template_userdata;
  565. tasks_posted[i] = task;
  566. // No task ID is used.
  567. }
  568. }
  569. groups[id] = group;
  570. _post_tasks(tasks_posted, p_tasks, p_high_priority, lock);
  571. return id;
  572. }
  573. 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) {
  574. return _add_group_task(Callable(), p_func, p_userdata, nullptr, p_elements, p_tasks, p_high_priority, p_description);
  575. }
  576. WorkerThreadPool::GroupID WorkerThreadPool::add_group_task(const Callable &p_action, int p_elements, int p_tasks, bool p_high_priority, const String &p_description) {
  577. return _add_group_task(p_action, nullptr, nullptr, nullptr, p_elements, p_tasks, p_high_priority, p_description);
  578. }
  579. uint32_t WorkerThreadPool::get_group_processed_element_count(GroupID p_group) const {
  580. MutexLock task_lock(task_mutex);
  581. const Group *const *groupp = groups.getptr(p_group);
  582. if (!groupp) {
  583. ERR_FAIL_V_MSG(0, "Invalid Group ID");
  584. }
  585. return (*groupp)->completed_index.get();
  586. }
  587. bool WorkerThreadPool::is_group_task_completed(GroupID p_group) const {
  588. MutexLock task_lock(task_mutex);
  589. const Group *const *groupp = groups.getptr(p_group);
  590. if (!groupp) {
  591. ERR_FAIL_V_MSG(false, "Invalid Group ID");
  592. }
  593. return (*groupp)->completed.is_set();
  594. }
  595. void WorkerThreadPool::wait_for_group_task_completion(GroupID p_group) {
  596. #ifdef THREADS_ENABLED
  597. task_mutex.lock();
  598. Group **groupp = groups.getptr(p_group);
  599. task_mutex.unlock();
  600. if (!groupp) {
  601. ERR_FAIL_MSG("Invalid Group ID.");
  602. }
  603. {
  604. Group *group = *groupp;
  605. if (this == singleton) {
  606. _unlock_unlockable_mutexes();
  607. }
  608. group->done_semaphore.wait();
  609. if (this == singleton) {
  610. _lock_unlockable_mutexes();
  611. }
  612. 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.
  613. uint32_t finished_users = group->finished.increment(); // fetch happens before inc, so increment later.
  614. if (finished_users == max_users) {
  615. // All tasks using this group are gone (finished before the group), so clear the group too.
  616. MutexLock task_lock(task_mutex);
  617. group_allocator.free(group);
  618. }
  619. }
  620. MutexLock task_lock(task_mutex); // This mutex is needed when Physics 2D and/or 3D is selected to run on a separate thread.
  621. groups.erase(p_group);
  622. #endif
  623. }
  624. int WorkerThreadPool::get_thread_index() const {
  625. Thread::ID tid = Thread::get_caller_id();
  626. return thread_ids.has(tid) ? thread_ids[tid] : -1;
  627. }
  628. WorkerThreadPool::TaskID WorkerThreadPool::get_caller_task_id() const {
  629. int th_index = get_thread_index();
  630. if (th_index != -1 && threads[th_index].current_task) {
  631. return threads[th_index].current_task->self;
  632. } else {
  633. return INVALID_TASK_ID;
  634. }
  635. }
  636. #ifdef THREADS_ENABLED
  637. uint32_t WorkerThreadPool::_thread_enter_unlock_allowance_zone(THREADING_NAMESPACE::unique_lock<THREADING_NAMESPACE::mutex> &p_ulock) {
  638. for (uint32_t i = 0; i < MAX_UNLOCKABLE_LOCKS; i++) {
  639. DEV_ASSERT((bool)unlockable_locks[i].ulock == (bool)unlockable_locks[i].rc);
  640. if (unlockable_locks[i].ulock == &p_ulock) {
  641. // Already registered in the current thread.
  642. unlockable_locks[i].rc++;
  643. return i;
  644. } else if (!unlockable_locks[i].ulock) {
  645. unlockable_locks[i].ulock = &p_ulock;
  646. unlockable_locks[i].rc = 1;
  647. return i;
  648. }
  649. }
  650. ERR_FAIL_V_MSG(UINT32_MAX, "No more unlockable lock slots available. Engine bug.");
  651. }
  652. void WorkerThreadPool::thread_exit_unlock_allowance_zone(uint32_t p_zone_id) {
  653. DEV_ASSERT(unlockable_locks[p_zone_id].ulock && unlockable_locks[p_zone_id].rc);
  654. unlockable_locks[p_zone_id].rc--;
  655. if (unlockable_locks[p_zone_id].rc == 0) {
  656. unlockable_locks[p_zone_id].ulock = nullptr;
  657. }
  658. }
  659. #endif
  660. void WorkerThreadPool::init(int p_thread_count, float p_low_priority_task_ratio) {
  661. ERR_FAIL_COND(threads.size() > 0);
  662. runlevel = RUNLEVEL_NORMAL;
  663. if (p_thread_count < 0) {
  664. p_thread_count = OS::get_singleton()->get_default_thread_pool_size();
  665. }
  666. max_low_priority_threads = CLAMP(p_thread_count * p_low_priority_task_ratio, 1, p_thread_count - 1);
  667. print_verbose(vformat("WorkerThreadPool: %d threads, %d max low-priority.", p_thread_count, max_low_priority_threads));
  668. threads.resize(p_thread_count);
  669. Thread::Settings settings;
  670. #ifdef __APPLE__
  671. // The default stack size for new threads on Apple platforms is 512KiB.
  672. // This is insufficient when using a library like SPIRV-Cross,
  673. // which can generate deep stacks and result in a stack overflow.
  674. #ifdef DEV_ENABLED
  675. // Debug builds need an even larger stack size.
  676. settings.stack_size = 2 * 1024 * 1024; // 2 MiB
  677. #else
  678. settings.stack_size = 1 * 1024 * 1024; // 1 MiB
  679. #endif
  680. #endif
  681. for (uint32_t i = 0; i < threads.size(); i++) {
  682. threads[i].index = i;
  683. threads[i].pool = this;
  684. threads[i].thread.start(&WorkerThreadPool::_thread_function, &threads[i], settings);
  685. thread_ids.insert(threads[i].thread.get_id(), i);
  686. }
  687. }
  688. void WorkerThreadPool::exit_languages_threads() {
  689. if (threads.is_empty()) {
  690. return;
  691. }
  692. MutexLock lock(task_mutex);
  693. // Wait until all threads are idle.
  694. _switch_runlevel(RUNLEVEL_PRE_EXIT_LANGUAGES);
  695. while (runlevel_data.pre_exit_languages.num_idle_threads != threads.size()) {
  696. control_cond_var.wait(lock);
  697. }
  698. // Wait until all threads have detached from scripting languages.
  699. _switch_runlevel(RUNLEVEL_EXIT_LANGUAGES);
  700. while (runlevel_data.exit_languages.num_exited_threads != threads.size()) {
  701. control_cond_var.wait(lock);
  702. }
  703. }
  704. void WorkerThreadPool::finish() {
  705. if (threads.is_empty()) {
  706. return;
  707. }
  708. {
  709. MutexLock lock(task_mutex);
  710. SelfList<Task> *E = low_priority_task_queue.first();
  711. while (E) {
  712. print_error("Task waiting was never re-claimed: " + E->self()->description);
  713. E = E->next();
  714. }
  715. _switch_runlevel(RUNLEVEL_EXIT);
  716. }
  717. for (ThreadData &data : threads) {
  718. data.thread.wait_to_finish();
  719. }
  720. {
  721. MutexLock lock(task_mutex);
  722. for (KeyValue<TaskID, Task *> &E : tasks) {
  723. task_allocator.free(E.value);
  724. }
  725. }
  726. threads.clear();
  727. }
  728. void WorkerThreadPool::_bind_methods() {
  729. ClassDB::bind_method(D_METHOD("add_task", "action", "high_priority", "description"), &WorkerThreadPool::add_task, DEFVAL(false), DEFVAL(String()));
  730. ClassDB::bind_method(D_METHOD("is_task_completed", "task_id"), &WorkerThreadPool::is_task_completed);
  731. ClassDB::bind_method(D_METHOD("wait_for_task_completion", "task_id"), &WorkerThreadPool::wait_for_task_completion);
  732. 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()));
  733. ClassDB::bind_method(D_METHOD("is_group_task_completed", "group_id"), &WorkerThreadPool::is_group_task_completed);
  734. ClassDB::bind_method(D_METHOD("get_group_processed_element_count", "group_id"), &WorkerThreadPool::get_group_processed_element_count);
  735. ClassDB::bind_method(D_METHOD("wait_for_group_task_completion", "group_id"), &WorkerThreadPool::wait_for_group_task_completion);
  736. }
  737. WorkerThreadPool *WorkerThreadPool::get_named_pool(const StringName &p_name) {
  738. WorkerThreadPool **pool_ptr = named_pools.getptr(p_name);
  739. if (pool_ptr) {
  740. return *pool_ptr;
  741. } else {
  742. WorkerThreadPool *pool = memnew(WorkerThreadPool(false));
  743. pool->init();
  744. named_pools[p_name] = pool;
  745. return pool;
  746. }
  747. }
  748. WorkerThreadPool::WorkerThreadPool(bool p_singleton) {
  749. if (p_singleton) {
  750. singleton = this;
  751. }
  752. }
  753. WorkerThreadPool::~WorkerThreadPool() {
  754. finish();
  755. if (this == singleton) {
  756. singleton = nullptr;
  757. for (KeyValue<StringName, WorkerThreadPool *> &E : named_pools) {
  758. E.value->finish();
  759. memdelete(E.value);
  760. }
  761. named_pools.clear();
  762. }
  763. }