From 873eb21ce81787fb67fb982684dc2bd5f71858ef Mon Sep 17 00:00:00 2001 From: HP van Braam Date: Fri, 3 Jan 2025 14:49:16 +0100 Subject: [PATCH] Optimize Thread::get_caller_id() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit By making sure that Thread always has a valid caller_id we can remove the check making the function a straightforward getter instead. In some quick tests we see a repeatable performance improvement of somewhere around 0.32 mspf in TPS demo. Co-authored-by: Pedro J. Estébanez --- core/os/thread.cpp | 2 +- core/os/thread.h | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/core/os/thread.cpp b/core/os/thread.cpp index 3992eb31bf5f..1214875032b9 100644 --- a/core/os/thread.cpp +++ b/core/os/thread.cpp @@ -38,8 +38,8 @@ #include "core/object/script_language.h" SafeNumeric Thread::id_counter(1); // The first value after .increment() is 2, hence by default the main thread ID should be 1. +thread_local Thread::ID Thread::caller_id = Thread::id_counter.increment(); -thread_local Thread::ID Thread::caller_id = Thread::UNASSIGNED_ID; #endif Thread::PlatformFunctions Thread::platform_functions; diff --git a/core/os/thread.h b/core/os/thread.h index 9042c6c01716..472998673a35 100644 --- a/core/os/thread.h +++ b/core/os/thread.h @@ -112,6 +112,7 @@ class Thread { static PlatformFunctions platform_functions; ID id = UNASSIGNED_ID; + static SafeNumeric id_counter; static thread_local ID caller_id; THREADING_NAMESPACE::thread thread; @@ -119,7 +120,7 @@ class Thread { static void callback(ID p_caller_id, const Settings &p_settings, Thread::Callback p_callback, void *p_userdata); static void make_main_thread() { caller_id = MAIN_ID; } - static void release_main_thread() { caller_id = UNASSIGNED_ID; } + static void release_main_thread() { caller_id = id_counter.increment(); } public: static void _set_platform_functions(const PlatformFunctions &p_functions); @@ -127,9 +128,6 @@ class Thread { _FORCE_INLINE_ ID get_id() const { return id; } // get the ID of the caller thread _FORCE_INLINE_ static ID get_caller_id() { - if (unlikely(caller_id == UNASSIGNED_ID)) { - caller_id = id_counter.increment(); - } return caller_id; } // get the ID of the main thread