Debian Codegraph @

core/object/worker_thread_pool.h

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