worker_thread_pool.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 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. Group *group = nullptr;
  77. SelfList<Task> task_elem;
  78. uint32_t waiting_pool = 0;
  79. uint32_t waiting_user = 0;
  80. bool low_priority = false;
  81. BaseTemplateUserdata *template_userdata = nullptr;
  82. int pool_thread_index = -1;
  83. void free_template_userdata();
  84. Task() :
  85. completed(false),
  86. pending_notify_yield_over(false),
  87. task_elem(this) {}
  88. };
  89. static const uint32_t TASKS_PAGE_SIZE = 1024;
  90. static const uint32_t GROUPS_PAGE_SIZE = 256;
  91. PagedAllocator<Task, false, TASKS_PAGE_SIZE> task_allocator;
  92. PagedAllocator<Group, false, GROUPS_PAGE_SIZE> group_allocator;
  93. SelfList<Task>::List low_priority_task_queue;
  94. SelfList<Task>::List task_queue;
  95. BinaryMutex task_mutex;
  96. struct ThreadData {
  97. static Task *const YIELDING; // Too bad constexpr doesn't work here.
  98. uint32_t index = 0;
  99. Thread thread;
  100. bool signaled : 1;
  101. bool yield_is_over : 1;
  102. bool pre_exited_languages : 1;
  103. bool exited_languages : 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. signaled(false),
  109. yield_is_over(false),
  110. pre_exited_languages(false),
  111. exited_languages(false) {}
  112. };
  113. TightLocalVector<ThreadData> threads;
  114. enum Runlevel {
  115. RUNLEVEL_NORMAL,
  116. RUNLEVEL_PRE_EXIT_LANGUAGES, // Block adding new tasks
  117. RUNLEVEL_EXIT_LANGUAGES, // All threads detach from scripting threads.
  118. RUNLEVEL_EXIT,
  119. } runlevel = RUNLEVEL_NORMAL;
  120. union { // Cleared on every runlevel change.
  121. struct {
  122. uint32_t num_idle_threads;
  123. } pre_exit_languages;
  124. struct {
  125. uint32_t num_exited_threads;
  126. } exit_languages;
  127. } runlevel_data;
  128. ConditionVariable control_cond_var;
  129. HashMap<Thread::ID, int> thread_ids;
  130. HashMap<
  131. TaskID,
  132. Task *,
  133. HashMapHasherDefault,
  134. HashMapComparatorDefault<TaskID>,
  135. PagedAllocator<HashMapElement<TaskID, Task *>, false, TASKS_PAGE_SIZE>>
  136. tasks;
  137. HashMap<
  138. GroupID,
  139. Group *,
  140. HashMapHasherDefault,
  141. HashMapComparatorDefault<GroupID>,
  142. PagedAllocator<HashMapElement<GroupID, Group *>, false, GROUPS_PAGE_SIZE>>
  143. groups;
  144. uint32_t max_low_priority_threads = 0;
  145. uint32_t low_priority_threads_used = 0;
  146. uint32_t notify_index = 0; // For rotating across threads, no help distributing load.
  147. uint64_t last_task = 1;
  148. static void _thread_function(void *p_user);
  149. void _process_task(Task *task);
  150. void _post_tasks(Task **p_tasks, uint32_t p_count, bool p_high_priority, MutexLock<BinaryMutex> &p_lock);
  151. void _notify_threads(const ThreadData *p_current_thread_data, uint32_t p_process_count, uint32_t p_promote_count);
  152. bool _try_promote_low_priority_task();
  153. static WorkerThreadPool *singleton;
  154. #ifdef THREADS_ENABLED
  155. static const uint32_t MAX_UNLOCKABLE_LOCKS = 2;
  156. struct UnlockableLocks {
  157. THREADING_NAMESPACE::unique_lock<THREADING_NAMESPACE::mutex> *ulock = nullptr;
  158. uint32_t rc = 0;
  159. };
  160. static thread_local UnlockableLocks unlockable_locks[MAX_UNLOCKABLE_LOCKS];
  161. #endif
  162. 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);
  163. 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);
  164. template <typename C, typename M, typename U>
  165. struct TaskUserData : public BaseTemplateUserdata {
  166. C *instance;
  167. M method;
  168. U userdata;
  169. virtual void callback() override {
  170. (instance->*method)(userdata);
  171. }
  172. };
  173. template <typename C, typename M, typename U>
  174. struct GroupUserData : public BaseTemplateUserdata {
  175. C *instance;
  176. M method;
  177. U userdata;
  178. virtual void callback_indexed(uint32_t p_index) override {
  179. (instance->*method)(p_index, userdata);
  180. }
  181. };
  182. void _wait_collaboratively(ThreadData *p_caller_pool_thread, Task *p_task);
  183. void _switch_runlevel(Runlevel p_runlevel);
  184. bool _handle_runlevel(ThreadData *p_thread_data, MutexLock<BinaryMutex> &p_lock);
  185. #ifdef THREADS_ENABLED
  186. static uint32_t _thread_enter_unlock_allowance_zone(THREADING_NAMESPACE::unique_lock<THREADING_NAMESPACE::mutex> &p_ulock);
  187. #endif
  188. void _lock_unlockable_mutexes();
  189. void _unlock_unlockable_mutexes();
  190. protected:
  191. static void _bind_methods();
  192. public:
  193. template <typename C, typename M, typename U>
  194. TaskID add_template_task(C *p_instance, M p_method, U p_userdata, bool p_high_priority = false, const String &p_description = String()) {
  195. typedef TaskUserData<C, M, U> TUD;
  196. TUD *ud = memnew(TUD);
  197. ud->instance = p_instance;
  198. ud->method = p_method;
  199. ud->userdata = p_userdata;
  200. return _add_task(Callable(), nullptr, nullptr, ud, p_high_priority, p_description);
  201. }
  202. TaskID add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority = false, const String &p_description = String());
  203. TaskID add_task(const Callable &p_action, bool p_high_priority = false, const String &p_description = String());
  204. bool is_task_completed(TaskID p_task_id) const;
  205. Error wait_for_task_completion(TaskID p_task_id);
  206. void yield();
  207. void notify_yield_over(TaskID p_task_id);
  208. template <typename C, typename M, typename U>
  209. 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()) {
  210. typedef GroupUserData<C, M, U> GroupUD;
  211. GroupUD *ud = memnew(GroupUD);
  212. ud->instance = p_instance;
  213. ud->method = p_method;
  214. ud->userdata = p_userdata;
  215. return _add_group_task(Callable(), nullptr, nullptr, ud, p_elements, p_tasks, p_high_priority, p_description);
  216. }
  217. 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());
  218. 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());
  219. uint32_t get_group_processed_element_count(GroupID p_group) const;
  220. bool is_group_task_completed(GroupID p_group) const;
  221. void wait_for_group_task_completion(GroupID p_group);
  222. _FORCE_INLINE_ int get_thread_count() const { return threads.size(); }
  223. static WorkerThreadPool *get_singleton() { return singleton; }
  224. static int get_thread_index();
  225. static TaskID get_caller_task_id();
  226. #ifdef THREADS_ENABLED
  227. _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()); }
  228. template <int Tag>
  229. _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()); }
  230. static void thread_exit_unlock_allowance_zone(uint32_t p_zone_id);
  231. #else
  232. static uint32_t thread_enter_unlock_allowance_zone(const MutexLock<BinaryMutex> &p_lock) { return UINT32_MAX; }
  233. template <int Tag>
  234. static uint32_t thread_enter_unlock_allowance_zone(const SafeBinaryMutex<Tag> &p_mutex) { return UINT32_MAX; }
  235. static void thread_exit_unlock_allowance_zone(uint32_t p_zone_id) {}
  236. #endif
  237. void init(int p_thread_count = -1, float p_low_priority_task_ratio = 0.3);
  238. void exit_languages_threads();
  239. void finish();
  240. WorkerThreadPool();
  241. ~WorkerThreadPool();
  242. };
  243. #endif // WORKER_THREAD_POOL_H