worker_thread_pool.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. #ifndef WORKER_THREAD_POOL_H
  31. #define WORKER_THREAD_POOL_H
  32. #include "core/os/condition_variable.h"
  33. #include "core/os/memory.h"
  34. #include "core/os/os.h"
  35. #include "core/os/semaphore.h"
  36. #include "core/os/thread.h"
  37. #include "core/templates/local_vector.h"
  38. #include "core/templates/paged_allocator.h"
  39. #include "core/templates/rid.h"
  40. #include "core/templates/safe_refcount.h"
  41. class CommandQueueMT;
  42. class WorkerThreadPool : public Object {
  43. GDCLASS(WorkerThreadPool, Object)
  44. public:
  45. enum {
  46. INVALID_TASK_ID = -1
  47. };
  48. typedef int64_t TaskID;
  49. typedef int64_t GroupID;
  50. private:
  51. struct Task;
  52. struct BaseTemplateUserdata {
  53. virtual void callback() {}
  54. virtual void callback_indexed(uint32_t p_index) {}
  55. virtual ~BaseTemplateUserdata() {}
  56. };
  57. struct Group {
  58. GroupID self = -1;
  59. SafeNumeric<uint32_t> index;
  60. SafeNumeric<uint32_t> completed_index;
  61. uint32_t max = 0;
  62. Semaphore done_semaphore;
  63. SafeFlag completed;
  64. SafeNumeric<uint32_t> finished;
  65. uint32_t tasks_used = 0;
  66. };
  67. struct Task {
  68. TaskID self = -1;
  69. Callable callable;
  70. void (*native_func)(void *) = nullptr;
  71. void (*native_group_func)(void *, uint32_t) = nullptr;
  72. void *native_func_userdata = nullptr;
  73. String description;
  74. Semaphore done_semaphore; // For user threads awaiting.
  75. bool completed : 1;
  76. bool pending_notify_yield_over : 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. task_elem(this) {}
  89. };
  90. static const uint32_t TASKS_PAGE_SIZE = 1024;
  91. static const uint32_t GROUPS_PAGE_SIZE = 256;
  92. PagedAllocator<Task, false, TASKS_PAGE_SIZE> task_allocator;
  93. PagedAllocator<Group, false, GROUPS_PAGE_SIZE> group_allocator;
  94. SelfList<Task>::List low_priority_task_queue;
  95. SelfList<Task>::List task_queue;
  96. BinaryMutex task_mutex;
  97. struct ThreadData {
  98. static Task *const YIELDING; // Too bad constexpr doesn't work here.
  99. uint32_t index = 0;
  100. Thread thread;
  101. bool ready_for_scripting : 1;
  102. bool signaled : 1;
  103. bool yield_is_over : 1;
  104. Task *current_task = nullptr;
  105. Task *awaited_task = nullptr; // Null if not awaiting the condition variable, or special value (YIELDING).
  106. ConditionVariable cond_var;
  107. ThreadData() :
  108. ready_for_scripting(false),
  109. signaled(false),
  110. yield_is_over(false) {}
  111. };
  112. TightLocalVector<ThreadData> threads;
  113. bool exit_threads = false;
  114. HashMap<Thread::ID, int> thread_ids;
  115. HashMap<
  116. TaskID,
  117. Task *,
  118. HashMapHasherDefault,
  119. HashMapComparatorDefault<TaskID>,
  120. PagedAllocator<HashMapElement<TaskID, Task *>, false, TASKS_PAGE_SIZE>>
  121. tasks;
  122. HashMap<
  123. GroupID,
  124. Group *,
  125. HashMapHasherDefault,
  126. HashMapComparatorDefault<GroupID>,
  127. PagedAllocator<HashMapElement<GroupID, Group *>, false, GROUPS_PAGE_SIZE>>
  128. groups;
  129. uint32_t max_low_priority_threads = 0;
  130. uint32_t low_priority_threads_used = 0;
  131. uint32_t notify_index = 0; // For rotating across threads, no help distributing load.
  132. uint64_t last_task = 1;
  133. static void _thread_function(void *p_user);
  134. void _process_task(Task *task);
  135. void _post_tasks_and_unlock(Task **p_tasks, uint32_t p_count, bool p_high_priority);
  136. void _notify_threads(const ThreadData *p_current_thread_data, uint32_t p_process_count, uint32_t p_promote_count);
  137. bool _try_promote_low_priority_task();
  138. static WorkerThreadPool *singleton;
  139. static thread_local CommandQueueMT *flushing_cmd_queue;
  140. 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);
  141. 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);
  142. template <typename C, typename M, typename U>
  143. struct TaskUserData : public BaseTemplateUserdata {
  144. C *instance;
  145. M method;
  146. U userdata;
  147. virtual void callback() override {
  148. (instance->*method)(userdata);
  149. }
  150. };
  151. template <typename C, typename M, typename U>
  152. struct GroupUserData : public BaseTemplateUserdata {
  153. C *instance;
  154. M method;
  155. U userdata;
  156. virtual void callback_indexed(uint32_t p_index) override {
  157. (instance->*method)(p_index, userdata);
  158. }
  159. };
  160. void _wait_collaboratively(ThreadData *p_caller_pool_thread, Task *p_task);
  161. protected:
  162. static void _bind_methods();
  163. public:
  164. template <typename C, typename M, typename U>
  165. TaskID add_template_task(C *p_instance, M p_method, U p_userdata, bool p_high_priority = false, const String &p_description = String()) {
  166. typedef TaskUserData<C, M, U> TUD;
  167. TUD *ud = memnew(TUD);
  168. ud->instance = p_instance;
  169. ud->method = p_method;
  170. ud->userdata = p_userdata;
  171. return _add_task(Callable(), nullptr, nullptr, ud, p_high_priority, p_description);
  172. }
  173. TaskID add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority = false, const String &p_description = String());
  174. TaskID add_task(const Callable &p_action, bool p_high_priority = false, const String &p_description = String());
  175. bool is_task_completed(TaskID p_task_id) const;
  176. Error wait_for_task_completion(TaskID p_task_id);
  177. void yield();
  178. void notify_yield_over(TaskID p_task_id);
  179. template <typename C, typename M, typename U>
  180. 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()) {
  181. typedef GroupUserData<C, M, U> GroupUD;
  182. GroupUD *ud = memnew(GroupUD);
  183. ud->instance = p_instance;
  184. ud->method = p_method;
  185. ud->userdata = p_userdata;
  186. return _add_group_task(Callable(), nullptr, nullptr, ud, p_elements, p_tasks, p_high_priority, p_description);
  187. }
  188. 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());
  189. 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());
  190. uint32_t get_group_processed_element_count(GroupID p_group) const;
  191. bool is_group_task_completed(GroupID p_group) const;
  192. void wait_for_group_task_completion(GroupID p_group);
  193. _FORCE_INLINE_ int get_thread_count() const { return threads.size(); }
  194. static WorkerThreadPool *get_singleton() { return singleton; }
  195. static int get_thread_index();
  196. static void thread_enter_command_queue_mt_flush(CommandQueueMT *p_queue);
  197. static void thread_exit_command_queue_mt_flush();
  198. void init(int p_thread_count = -1, float p_low_priority_task_ratio = 0.3);
  199. void finish();
  200. WorkerThreadPool();
  201. ~WorkerThreadPool();
  202. };
  203. #endif // WORKER_THREAD_POOL_H