worker_thread_pool.cpp 22 KB

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