mirror of
https://github.com/libsdl-org/SDL.git
synced 2025-10-14 13:56:00 +00:00
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:

committed by
Ryan C. Gordon

parent
e9a93246ef
commit
64acde86de
@@ -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
|
||||
|
Reference in New Issue
Block a user