stdcpp threads, simplify SDL_GetCurrentThreadID implementation

Removed the workaround that handrolled a thread id using a thread_local variable alongside static mutexes
This commit is contained in:
Edoardo Lolletti
2024-06-24 22:31:32 +02:00
committed by Ryan C. Gordon
parent e9a93246ef
commit 64acde86de

View File

@@ -27,7 +27,6 @@ extern "C" {
#include "../SDL_systhread.h" #include "../SDL_systhread.h"
} }
#include <mutex>
#include <thread> #include <thread>
#include <system_error> #include <system_error>
@@ -47,11 +46,10 @@ SDL_SYS_CreateThread(SDL_Thread *thread,
{ {
try { try {
// !!! FIXME: no way to set a thread stack size here. // !!! FIXME: no way to set a thread stack size here.
std::thread cpp_thread(RunThread, thread); thread->handle = (void *)new std::thread(RunThread, thread);
thread->handle = (void *)new std::thread(std::move(cpp_thread));
return 0; return 0;
} catch (std::system_error &ex) { } 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 &) { } catch (std::bad_alloc &) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -60,30 +58,17 @@ SDL_SYS_CreateThread(SDL_Thread *thread,
extern "C" void extern "C" void
SDL_SYS_SetupThread(const char *name) SDL_SYS_SetupThread(const char *name)
{ {
// Make sure a thread ID gets assigned ASAP, for debugging purposes: /* Do nothing. */
SDL_GetCurrentThreadID();
return;
} }
extern "C" SDL_ThreadID extern "C" SDL_ThreadID
SDL_GetCurrentThreadID(void) SDL_GetCurrentThreadID(void)
{ {
#ifdef SDL_PLATFORM_WINRT static_assert(sizeof(std::thread::id) <= sizeof(SDL_ThreadID), "std::thread::id must not be bigger than SDL_ThreadID");
return GetCurrentThreadId(); SDL_ThreadID thread_id{};
#else const auto cpp_thread_id = std::this_thread::get_id();
// HACK: Mimic a thread ID, if one isn't otherwise available. SDL_memcpy(&thread_id, &cpp_thread_id, sizeof(std::thread::id));
static thread_local SDL_ThreadID current_thread_id = 0; return thread_id;
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
} }
extern "C" int extern "C" int