Skip to content

Commit fc1dbda

Browse files
committed
Merge pull request godotengine#105164 from stuartcarnie/apple_pthread
Apple: Add pthread implementation of `Thread` class
2 parents c85e122 + 8c8d6de commit fc1dbda

File tree

12 files changed

+336
-2
lines changed

12 files changed

+336
-2
lines changed

core/object/worker_thread_pool.cpp

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -780,10 +780,23 @@ void WorkerThreadPool::init(int p_thread_count, float p_low_priority_task_ratio)
780780

781781
threads.resize(p_thread_count);
782782

783+
Thread::Settings settings;
784+
#ifdef __APPLE__
785+
// The default stack size for new threads on Apple platforms is 512KiB.
786+
// This is insufficient when using a library like SPIRV-Cross,
787+
// which can generate deep stacks and result in a stack overflow.
788+
#ifdef DEV_ENABLED
789+
// Debug builds need an even larger stack size.
790+
settings.stack_size = 2 * 1024 * 1024; // 2 MiB
791+
#else
792+
settings.stack_size = 1 * 1024 * 1024; // 1 MiB
793+
#endif
794+
#endif
795+
783796
for (uint32_t i = 0; i < threads.size(); i++) {
784797
threads[i].index = i;
785798
threads[i].pool = this;
786-
threads[i].thread.start(&WorkerThreadPool::_thread_function, &threads[i]);
799+
threads[i].thread.start(&WorkerThreadPool::_thread_function, &threads[i], settings);
787800
thread_ids.insert(threads[i].thread.get_id(), i);
788801
}
789802
}

core/os/thread.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ class Thread {
119119
public:
120120
static void _set_platform_functions(const PlatformFunctions &p_functions);
121121

122+
_FORCE_INLINE_ static void yield() { std::this_thread::yield(); }
123+
122124
_FORCE_INLINE_ ID get_id() const { return id; }
123125
// get the ID of the caller thread
124126
_FORCE_INLINE_ static ID get_caller_id() {

drivers/apple/SCsub

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ Import("env")
55

66
# Driver source files
77
env.add_source_files(env.drivers_sources, "*.mm")
8+
env.add_source_files(env.drivers_sources, "*.cpp")

drivers/apple/thread_apple.cpp

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
/**************************************************************************/
2+
/* thread_apple.cpp */
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+
#include "thread_apple.h"
32+
33+
#include "core/error/error_macros.h"
34+
#include "core/object/script_language.h"
35+
#include "core/string/ustring.h"
36+
37+
SafeNumeric<uint64_t> Thread::id_counter(1); // The first value after .increment() is 2, hence by default the main thread ID should be 1.
38+
thread_local Thread::ID Thread::caller_id = Thread::id_counter.increment();
39+
40+
struct ThreadData {
41+
Thread::Callback callback;
42+
void *userdata;
43+
Thread::ID caller_id;
44+
};
45+
46+
void *Thread::thread_callback(void *p_data) {
47+
ThreadData *thread_data = static_cast<ThreadData *>(p_data);
48+
49+
// Set the caller ID for this thread
50+
caller_id = thread_data->caller_id;
51+
52+
ScriptServer::thread_enter(); // Scripts may need to attach a stack.
53+
54+
// Call the actual callback
55+
thread_data->callback(thread_data->userdata);
56+
57+
ScriptServer::thread_exit();
58+
59+
// Clean up
60+
memdelete(thread_data);
61+
62+
return nullptr;
63+
}
64+
65+
Error Thread::set_name(const String &p_name) {
66+
int err = pthread_setname_np(p_name.utf8().get_data());
67+
return err == 0 ? OK : ERR_INVALID_PARAMETER;
68+
}
69+
70+
Thread::ID Thread::start(Thread::Callback p_callback, void *p_user, const Settings &p_settings) {
71+
ERR_FAIL_COND_V_MSG(id != UNASSIGNED_ID, UNASSIGNED_ID, "A Thread object has been re-started without wait_to_finish() having been called on it.");
72+
id = id_counter.increment();
73+
74+
ThreadData *thread_data = memnew(ThreadData);
75+
thread_data->callback = p_callback;
76+
thread_data->userdata = p_user;
77+
thread_data->caller_id = id;
78+
79+
// Create the thread
80+
pthread_attr_t attr;
81+
pthread_attr_init(&attr);
82+
83+
switch (p_settings.priority) {
84+
case PRIORITY_LOW:
85+
pthread_attr_set_qos_class_np(&attr, QOS_CLASS_UTILITY, 0);
86+
break;
87+
case PRIORITY_NORMAL:
88+
pthread_attr_set_qos_class_np(&attr, QOS_CLASS_USER_INITIATED, 0);
89+
break;
90+
case PRIORITY_HIGH:
91+
pthread_attr_set_qos_class_np(&attr, QOS_CLASS_USER_INTERACTIVE, 0);
92+
break;
93+
}
94+
95+
if (p_settings.stack_size > 0) {
96+
pthread_attr_setstacksize(&attr, p_settings.stack_size);
97+
}
98+
99+
// Create the thread
100+
pthread_create(&pthread, &attr, thread_callback, thread_data);
101+
102+
// Clean up attributes
103+
pthread_attr_destroy(&attr);
104+
105+
return id;
106+
}
107+
108+
void Thread::wait_to_finish() {
109+
ERR_FAIL_COND_MSG(id == UNASSIGNED_ID, "Attempt of waiting to finish on a thread that was never started.");
110+
ERR_FAIL_COND_MSG(id == get_caller_id(), "Threads can't wait to finish on themselves, another thread must wait.");
111+
112+
int err = pthread_join(pthread, nullptr);
113+
if (err != 0) {
114+
ERR_FAIL_MSG("Thread::wait_to_finish() failed to join thread.");
115+
}
116+
pthread = pthread_t();
117+
id = UNASSIGNED_ID;
118+
}
119+
120+
Thread::~Thread() {
121+
if (id != UNASSIGNED_ID) {
122+
#ifdef DEBUG_ENABLED
123+
WARN_PRINT(
124+
"A Thread object is being destroyed without its completion having been realized.\n"
125+
"Please call wait_to_finish() on it to ensure correct cleanup.");
126+
#endif
127+
pthread_detach(pthread);
128+
}
129+
}

drivers/apple/thread_apple.h

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**************************************************************************/
2+
/* thread_apple.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/templates/safe_refcount.h"
34+
#include "core/typedefs.h"
35+
36+
#include <pthread.h>
37+
#include <new> // For hardware interference size
38+
39+
class String;
40+
41+
class Thread {
42+
public:
43+
typedef void (*Callback)(void *p_userdata);
44+
45+
typedef uint64_t ID;
46+
47+
enum : ID {
48+
UNASSIGNED_ID = 0,
49+
MAIN_ID = 1
50+
};
51+
52+
enum Priority {
53+
PRIORITY_LOW,
54+
PRIORITY_NORMAL,
55+
PRIORITY_HIGH
56+
};
57+
58+
struct Settings {
59+
Priority priority;
60+
/// Override the default stack size (0 means default)
61+
uint64_t stack_size = 0;
62+
Settings() { priority = PRIORITY_NORMAL; }
63+
};
64+
65+
#if defined(__cpp_lib_hardware_interference_size)
66+
GODOT_GCC_WARNING_PUSH_AND_IGNORE("-Winterference-size")
67+
static constexpr size_t CACHE_LINE_BYTES = std::hardware_destructive_interference_size;
68+
GODOT_GCC_WARNING_POP
69+
#else
70+
// At a negligible memory cost, we use a conservatively high value.
71+
static constexpr size_t CACHE_LINE_BYTES = 128;
72+
#endif
73+
74+
private:
75+
friend class Main;
76+
77+
ID id = UNASSIGNED_ID;
78+
pthread_t pthread;
79+
80+
static SafeNumeric<uint64_t> id_counter;
81+
static thread_local ID caller_id;
82+
83+
static void *thread_callback(void *p_data);
84+
85+
static void make_main_thread() { caller_id = MAIN_ID; }
86+
static void release_main_thread() { caller_id = id_counter.increment(); }
87+
88+
public:
89+
_FORCE_INLINE_ static void yield() { pthread_yield_np(); }
90+
91+
_FORCE_INLINE_ ID get_id() const { return id; }
92+
// get the ID of the caller thread
93+
_FORCE_INLINE_ static ID get_caller_id() {
94+
return caller_id;
95+
}
96+
// get the ID of the main thread
97+
_FORCE_INLINE_ static ID get_main_id() { return MAIN_ID; }
98+
99+
_FORCE_INLINE_ static bool is_main_thread() { return caller_id == MAIN_ID; }
100+
101+
static Error set_name(const String &p_name);
102+
103+
ID start(Thread::Callback p_callback, void *p_user, const Settings &p_settings = Settings());
104+
bool is_started() const { return id != UNASSIGNED_ID; }
105+
/// Waits until thread is finished, and deallocates it.
106+
void wait_to_finish();
107+
108+
Thread() = default;
109+
~Thread();
110+
};

drivers/metal/metal_utils.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232

3333
#import <os/log.h>
3434

35+
#import <functional>
36+
3537
#pragma mark - Boolean flags
3638

3739
namespace flags {

drivers/unix/thread_posix.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@
3535
#include "core/os/thread.h"
3636
#include "core/string/ustring.h"
3737

38+
#if defined(PLATFORM_THREAD_OVERRIDE) && defined(__APPLE__)
39+
void init_thread_posix() {
40+
}
41+
#else
42+
3843
#ifdef PTHREAD_BSD_SET_NAME
3944
#include <pthread_np.h>
4045
#endif
@@ -73,4 +78,6 @@ void init_thread_posix() {
7378
Thread::_set_platform_functions({ .set_name = set_name });
7479
}
7580

81+
#endif // PLATFORM_THREAD_OVERRIDE && __APPLE__
82+
7683
#endif // UNIX_ENABLED

platform/ios/platform_config.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232

3333
#include <alloca.h>
3434

35+
#define PLATFORM_THREAD_OVERRIDE
36+
3537
#define PTHREAD_RENAME_SELF
3638

3739
#define _weakify(var) __weak typeof(var) GDWeak_##var = var;

platform/ios/platform_thread.h

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**************************************************************************/
2+
/* platform_thread.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 "drivers/apple/thread_apple.h"

platform/macos/platform_config.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232

3333
#include <alloca.h>
3434

35+
#define PLATFORM_THREAD_OVERRIDE
36+
3537
#define PTHREAD_RENAME_SELF
3638

3739
#define _weakify(var) __weak typeof(var) GDWeak_##var = var;

0 commit comments

Comments
 (0)