worker_thread_pool.cpp 27 KB

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