Parcourir la source

stdcpp threads, simplify SDL_GetCurrentThreadID implementation

Removed the workaround that handrolled a thread id using a thread_local variable alongside static mutexes
Edoardo Lolletti il y a 9 mois
Parent
commit
64acde86de
1 fichiers modifiés avec 8 ajouts et 23 suppressions
  1. 8 23
      src/thread/stdcpp/SDL_systhread.cpp

+ 8 - 23
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