worker_thread_pool.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /**************************************************************************/
  2. /* worker_thread_pool.h */
  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. #pragma once
  31. #include "core/os/condition_variable.h"
  32. #include "core/os/memory.h"
  33. #include "core/os/os.h"
  34. #include "core/os/semaphore.h"
  35. #include "core/os/thread.h"
  36. #include "core/templates/local_vector.h"
  37. #include "core/templates/paged_allocator.h"
  38. #include "core/templates/rid.h"
  39. #include "core/templates/safe_refcount.h"
  40. #include "core/templates/self_list.h"
  41. class WorkerThreadPool : public Object {
  42. GDCLASS(WorkerThreadPool, Object)
  43. public:
  44. enum {
  45. INVALID_TASK_ID = -1
  46. };
  47. typedef int64_t TaskID;
  48. typedef int64_t GroupID;
  49. private:
  50. struct Task;
  51. struct BaseTemplateUserdata {
  52. virtual void callback() {}
  53. virtual void callback_indexed(uint32_t p_index) {}
  54. virtual ~BaseTemplateUserdata() {}
  55. };
  56. struct Group {
  57. GroupID self = -1;
  58. SafeNumeric<uint32_t> index;
  59. SafeNumeric<uint32_t> completed_index;
  60. uint32_t max = 0;
  61. Semaphore done_semaphore;
  62. SafeFlag completed;
  63. SafeNumeric<uint32_t> finished;
  64. uint32_t tasks_used = 0;
  65. };
  66. struct Task {
  67. TaskID self = -1;
  68. Callable callable;
  69. void (*native_func)(void *) = nullptr;
  70. void (*native_group_func)(void *, uint32_t) = nullptr;
  71. void *native_func_userdata = nullptr;
  72. String description;
  73. Semaphore done_semaphore; // For user threads awaiting.
  74. bool completed : 1;
  75. bool pending_notify_yield_over : 1;
  76. bool is_pump_task : 1;
  77. Group *group = nullptr;
  78. SelfList<Task> task_elem;
  79. uint32_t waiting_pool = 0;
  80. uint32_t waiting_user = 0;
  81. bool low_priority = false;
  82. BaseTemplateUserdata *template_userdata = nullptr;
  83. int pool_thread_index = -1;
  84. void free_template_userdata();
  85. Task() :
  86. completed(false),
  87. pending_notify_yield_over(false),
  88. is_pump_task(false),
  89. task_elem(this) {}
  90. };
  91. static const uint32_t TASKS_PAGE_SIZE = 1024;
  92. static const uint32_t GROUPS_PAGE_SIZE = 256;
  93. PagedAllocator<Task, false, TASKS_PAGE_SIZE> task_allocator;
  94. PagedAllocator<Group, false, GROUPS_PAGE_SIZE> group_allocator;
  95. SelfList<Task>::List low_priority_task_queue;
  96. SelfList<Task>::List task_queue;
  97. BinaryMutex task_mutex;
  98. struct ThreadData {
  99. static Task *const YIELDING; // Too bad constexpr doesn't work here.
  100. uint32_t index = 0;
  101. Thread thread;
  102. bool signaled : 1;
  103. bool yield_is_over : 1;
  104. bool pre_exited_languages : 1;
  105. bool exited_languages : 1;
  106. bool has_pump_task : 1; // Threads can only have one pump task.
  107. Task *current_task = nullptr;
  108. Task *awaited_task = nullptr; // Null if not awaiting the condition variable, or special value (YIELDING).
  109. ConditionVariable cond_var;
  110. WorkerThreadPool *pool = nullptr;
  111. ThreadData() :
  112. signaled(false),
  113. yield_is_over(false),
  114. pre_exited_languages(false),
  115. exited_languages(false),
  116. has_pump_task(false) {}
  117. };
  118. TightLocalVector<ThreadData> threads;
  119. enum Runlevel {
  120. RUNLEVEL_NORMAL,
  121. RUNLEVEL_PRE_EXIT_LANGUAGES, // Block adding new tasks
  122. RUNLEVEL_EXIT_LANGUAGES, // All threads detach from scripting threads.
  123. RUNLEVEL_EXIT,
  124. } runlevel = RUNLEVEL_NORMAL;
  125. union { // Cleared on every runlevel change.
  126. struct {
  127. uint32_t num_idle_threads;
  128. } pre_exit_languages;
  129. struct {
  130. uint32_t num_exited_threads;
  131. } exit_languages;
  132. } runlevel_data;
  133. ConditionVariable control_cond_var;
  134. HashMap<Thread::ID, int> thread_ids;
  135. HashMap<
  136. TaskID,
  137. Task *,
  138. HashMapHasherDefault,
  139. HashMapComparatorDefault<TaskID>,
  140. PagedAllocator<HashMapElement<TaskID, Task *>, false, TASKS_PAGE_SIZE>>
  141. tasks;
  142. HashMap<
  143. GroupID,
  144. Group *,
  145. HashMapHasherDefault,
  146. HashMapComparatorDefault<GroupID>,
  147. PagedAllocator<HashMapElement<GroupID, Group *>, false, GROUPS_PAGE_SIZE>>
  148. groups;
  149. uint32_t max_low_priority_threads = 0;
  150. uint32_t low_priority_threads_used = 0;
  151. uint32_t notify_index = 0; // For rotating across threads, no help distributing load.
  152. uint64_t last_task = 1;
  153. int pump_task_count = 0;
  154. static HashMap<StringName, WorkerThreadPool *> named_pools;
  155. static void _thread_function(void *p_user);
  156. void _process_task(Task *task);
  157. void _post_tasks(Task **p_tasks, uint32_t p_count, bool p_high_priority, MutexLock<BinaryMutex> &p_lock, bool p_pump_task);
  158. void _notify_threads(const ThreadData *p_current_thread_data, uint32_t p_process_count, uint32_t p_promote_count);
  159. bool _try_promote_low_priority_task();
  160. static WorkerThreadPool *singleton;
  161. #ifdef THREADS_ENABLED
  162. static const uint32_t MAX_UNLOCKABLE_LOCKS = 2;
  163. struct UnlockableLocks {
  164. THREADING_NAMESPACE::unique_lock<THREADING_NAMESPACE::mutex> *ulock = nullptr;
  165. uint32_t rc = 0;
  166. };
  167. static thread_local UnlockableLocks unlockable_locks[MAX_UNLOCKABLE_LOCKS];
  168. #endif
  169. TaskID _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, bool p_pump_task = false);
  170. GroupID _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);
  171. template <typename C, typename M, typename U>
  172. struct TaskUserData : public BaseTemplateUserdata {
  173. C *instance;
  174. M method;
  175. U userdata;
  176. virtual void callback() override {
  177. (instance->*method)(userdata);
  178. }
  179. };
  180. template <typename C, typename M, typename U>
  181. struct GroupUserData : public BaseTemplateUserdata {
  182. C *instance;
  183. M method;
  184. U userdata;
  185. virtual void callback_indexed(uint32_t p_index) override {
  186. (instance->*method)(p_index, userdata);
  187. }
  188. };
  189. void _wait_collaboratively(ThreadData *p_caller_pool_thread, Task *p_task);
  190. void _switch_runlevel(Runlevel p_runlevel);
  191. bool _handle_runlevel(ThreadData *p_thread_data, MutexLock<BinaryMutex> &p_lock);
  192. #ifdef THREADS_ENABLED
  193. static uint32_t _thread_enter_unlock_allowance_zone(THREADING_NAMESPACE::unique_lock<THREADING_NAMESPACE::mutex> &p_ulock);
  194. #endif
  195. void _lock_unlockable_mutexes();
  196. void _unlock_unlockable_mutexes();
  197. protected:
  198. static void _bind_methods();
  199. public:
  200. template <typename C, typename M, typename U>
  201. TaskID add_template_task(C *p_instance, M p_method, U p_userdata, bool p_high_priority = false, const String &p_description = String()) {
  202. typedef TaskUserData<C, M, U> TUD;
  203. TUD *ud = memnew(TUD);
  204. ud->instance = p_instance;
  205. ud->method = p_method;
  206. ud->userdata = p_userdata;
  207. return _add_task(Callable(), nullptr, nullptr, ud, p_high_priority, p_description);
  208. }
  209. TaskID add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority = false, const String &p_description = String());
  210. TaskID add_task(const Callable &p_action, bool p_high_priority = false, const String &p_description = String(), bool p_pump_task = false);
  211. TaskID add_task_bind(const Callable &p_action, bool p_high_priority = false, const String &p_description = String());
  212. bool is_task_completed(TaskID p_task_id) const;
  213. Error wait_for_task_completion(TaskID p_task_id);
  214. void yield();
  215. void notify_yield_over(TaskID p_task_id);
  216. template <typename C, typename M, typename U>
  217. GroupID add_template_group_task(C *p_instance, M p_method, U p_userdata, int p_elements, int p_tasks = -1, bool p_high_priority = false, const String &p_description = String()) {
  218. typedef GroupUserData<C, M, U> GroupUD;
  219. GroupUD *ud = memnew(GroupUD);
  220. ud->instance = p_instance;
  221. ud->method = p_method;
  222. ud->userdata = p_userdata;
  223. return _add_group_task(Callable(), nullptr, nullptr, ud, p_elements, p_tasks, p_high_priority, p_description);
  224. }
  225. GroupID add_native_group_task(void (*p_func)(void *, uint32_t), void *p_userdata, int p_elements, int p_tasks = -1, bool p_high_priority = false, const String &p_description = String());
  226. GroupID add_group_task(const Callable &p_action, int p_elements, int p_tasks = -1, bool p_high_priority = false, const String &p_description = String());
  227. uint32_t get_group_processed_element_count(GroupID p_group) const;
  228. bool is_group_task_completed(GroupID p_group) const;
  229. void wait_for_group_task_completion(GroupID p_group);
  230. _FORCE_INLINE_ int get_thread_count() const {
  231. #ifdef THREADS_ENABLED
  232. return threads.size();
  233. #else
  234. return 1;
  235. #endif
  236. }
  237. // Note: Do not use this unless you know what you are doing, and it is absolutely necessary. Main thread pool (`get_singleton()`) should be preferred instead.
  238. static WorkerThreadPool *get_named_pool(const StringName &p_name);
  239. static WorkerThreadPool *get_singleton() { return singleton; }
  240. int get_thread_index() const;
  241. TaskID get_caller_task_id() const;
  242. GroupID get_caller_group_id() const;
  243. #ifdef THREADS_ENABLED
  244. _ALWAYS_INLINE_ static uint32_t thread_enter_unlock_allowance_zone(const MutexLock<BinaryMutex> &p_lock) { return _thread_enter_unlock_allowance_zone(p_lock._get_lock()); }
  245. template <int Tag>
  246. _ALWAYS_INLINE_ static uint32_t thread_enter_unlock_allowance_zone(const SafeBinaryMutex<Tag> &p_mutex) { return _thread_enter_unlock_allowance_zone(p_mutex._get_lock()); }
  247. static void thread_exit_unlock_allowance_zone(uint32_t p_zone_id);
  248. #else
  249. static uint32_t thread_enter_unlock_allowance_zone(const MutexLock<BinaryMutex> &p_lock) { return UINT32_MAX; }
  250. template <int Tag>
  251. static uint32_t thread_enter_unlock_allowance_zone(const SafeBinaryMutex<Tag> &p_mutex) { return UINT32_MAX; }
  252. static void thread_exit_unlock_allowance_zone(uint32_t p_zone_id) {}
  253. #endif
  254. void init(int p_thread_count = -1, float p_low_priority_task_ratio = 0.3);
  255. void exit_languages_threads();
  256. void finish();
  257. WorkerThreadPool(bool p_singleton = true);
  258. ~WorkerThreadPool();
  259. };