SDL: stdcpp threads, simplify SDL_GetCurrentThreadID implementation

From 64acde86de41c085947a2b25a63f9ae3e6038c51 Mon Sep 17 00:00:00 2001
From: Edoardo Lolletti <[EMAIL REDACTED]>
Date: Mon, 24 Jun 2024 22:31:32 +0200
Subject: [PATCH] stdcpp threads, simplify SDL_GetCurrentThreadID
 implementation

Removed the workaround that handrolled a thread id using a thread_local variable alongside static mutexes
---
 src/thread/stdcpp/SDL_systhread.cpp | 31 ++++++++---------------------
 1 file changed, 8 insertions(+), 23 deletions(-)

diff --git a/src/thread/stdcpp/SDL_systhread.cpp b/src/thread/stdcpp/SDL_systhread.cpp
index 350431f0ede03..a2b6f4a79bc37 100644
--- a/src/thread/stdcpp/SDL_systhread.cpp
+++ b/src/thread/stdcpp/SDL_systhread.cpp
@@ -27,7 +27,6 @@ extern "C" {
 #include "../SDL_systhread.h"
 }
 
-#include <mutex>
 #include <thread>
 #include <system_error>
 
@@ -47,11 +46,10 @@ SDL_SYS_CreateThread(SDL_Thread *thread,
 {
     try {
         // !!! FIXME: no way to set a thread stack size here.
-        std::thread cpp_thread(RunThread, thread);
-        thread->handle = (void *)new std::thread(std::move(cpp_thread));
+        thread->handle = (void *)new std::thread(RunThread, thread);
         return 0;
     } catch (std::system_error &ex) {
-        return SDL_SetError("unable to start a C++ thread: code=%d; %s", ex.code(), ex.what());
+        return SDL_SetError("unable to start a C++ thread: code=%d; %s", ex.code().value(), ex.what());
     } catch (std::bad_alloc &) {
         return SDL_OutOfMemory();
     }
@@ -60,30 +58,17 @@ SDL_SYS_CreateThread(SDL_Thread *thread,
 extern "C" void
 SDL_SYS_SetupThread(const char *name)
 {
-    // Make sure a thread ID gets assigned ASAP, for debugging purposes:
-    SDL_GetCurrentThreadID();
-    return;
+    /* Do nothing. */
 }
 
 extern "C" SDL_ThreadID
 SDL_GetCurrentThreadID(void)
 {
-#ifdef SDL_PLATFORM_WINRT
-    return GetCurrentThreadId();
-#else
-    // HACK: Mimic a thread ID, if one isn't otherwise available.
-    static thread_local SDL_ThreadID current_thread_id = 0;
-    static SDL_ThreadID next_thread_id = 1;
-    static std::mutex next_thread_id_mutex;
-
-    if (current_thread_id == 0) {
-        std::lock_guard<std::mutex> lock(next_thread_id_mutex);
-        current_thread_id = next_thread_id;
-        ++next_thread_id;
-    }
-
-    return current_thread_id;
-#endif
+    static_assert(sizeof(std::thread::id) <= sizeof(SDL_ThreadID), "std::thread::id must not be bigger than SDL_ThreadID");
+    SDL_ThreadID thread_id{};
+    const auto cpp_thread_id = std::this_thread::get_id();
+    SDL_memcpy(&thread_id, &cpp_thread_id, sizeof(std::thread::id));
+    return thread_id;
 }
 
 extern "C" int