From c6c195ff882ac83e395e50cb2235a22fbf762947 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Fri, 11 Oct 2024 21:00:09 -0700 Subject: [PATCH] Always use WaitForSingleObjectEx() as a fallback in SDL_SYS_DelayNS() That logic isn't specific to the Visual Studio build environment. Also switched it to use CreateEvent(), which works back to Windows XP. --- src/timer/windows/SDL_systimer.c | 52 ++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/src/timer/windows/SDL_systimer.c b/src/timer/windows/SDL_systimer.c index 087c0f3dbe..591dda3d78 100644 --- a/src/timer/windows/SDL_systimer.c +++ b/src/timer/windows/SDL_systimer.c @@ -25,13 +25,13 @@ #include "../../core/windows/SDL_windows.h" -#ifdef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION -static void SDL_CleanupWaitableTimer(void *timer) +static void SDL_CleanupWaitableHandle(void *handle) { - CloseHandle(timer); + CloseHandle(handle); } -HANDLE SDL_GetWaitableTimer(void) +#ifdef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION +static HANDLE SDL_GetWaitableTimer(void) { static SDL_TLSID TLS_timer_handle; HANDLE timer; @@ -40,13 +40,28 @@ HANDLE SDL_GetWaitableTimer(void) if (!timer) { timer = CreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); if (timer) { - SDL_SetTLS(&TLS_timer_handle, timer, SDL_CleanupWaitableTimer); + SDL_SetTLS(&TLS_timer_handle, timer, SDL_CleanupWaitableHandle); } } return timer; } #endif // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION +static HANDLE SDL_GetWaitableEvent(void) +{ + static SDL_TLSID TLS_event_handle; + HANDLE event; + + event = SDL_GetTLS(&TLS_event_handle); + if (!event) { + event = CreateEvent(NULL, FALSE, FALSE, NULL); + if (event) { + SDL_SetTLS(&TLS_event_handle, event, SDL_CleanupWaitableHandle); + } + } + return event; +} + Uint64 SDL_GetPerformanceCounter(void) { LARGE_INTEGER counter; @@ -81,22 +96,19 @@ void SDL_SYS_DelayNS(Uint64 ns) } #endif - { - const Uint64 max_delay = 0xffffffffLL * SDL_NS_PER_MS; - if (ns > max_delay) { - ns = max_delay; - } - -#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER <= 180030723) - static HANDLE mutex = 0; - if (!mutex) { - mutex = CreateEventEx(0, 0, 0, EVENT_ALL_ACCESS); - } - WaitForSingleObjectEx(mutex, (DWORD)SDL_NS_TO_MS(ns), FALSE); -#else - Sleep((DWORD)SDL_NS_TO_MS(ns)); -#endif + const Uint64 max_delay = 0xffffffffLL * SDL_NS_PER_MS; + if (ns > max_delay) { + ns = max_delay; } + const DWORD delay = (DWORD)SDL_NS_TO_MS(ns); + + HANDLE event = SDL_GetWaitableEvent(); + if (event) { + WaitForSingleObjectEx(event, delay, FALSE); + return; + } + + Sleep(delay); } #endif // SDL_TIMER_WINDOWS