worker_thread_pool.cpp 25 KB

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