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