Path: blob/master/thirdparty/sdl/thread/windows/SDL_syssem.c
9905 views
/*1Simple DirectMedia Layer2Copyright (C) 1997-2025 Sam Lantinga <[email protected]>34This software is provided 'as-is', without any express or implied5warranty. In no event will the authors be held liable for any damages6arising from the use of this software.78Permission is granted to anyone to use this software for any purpose,9including commercial applications, and to alter it and redistribute it10freely, subject to the following restrictions:11121. The origin of this software must not be misrepresented; you must not13claim that you wrote the original software. If you use this software14in a product, an acknowledgment in the product documentation would be15appreciated but is not required.162. Altered source versions must be plainly marked as such, and must not be17misrepresented as being the original software.183. This notice may not be removed or altered from any source distribution.19*/20#include "SDL_internal.h"2122#ifdef SDL_THREAD_WINDOWS2324/**25* Semaphore functions using the Win32 API26* There are two implementations available based on:27* - Kernel Semaphores. Available on all OS versions. (kern)28* Heavy-weight inter-process kernel objects.29* - Atomics and WaitOnAddress API. (atom)30* Faster due to significantly less context switches.31* Requires Windows 8 or newer.32* which are chosen at runtime.33*/3435#include "../../core/windows/SDL_windows.h"3637typedef SDL_Semaphore *(*pfnSDL_CreateSemaphore)(Uint32);38typedef void (*pfnSDL_DestroySemaphore)(SDL_Semaphore *);39typedef bool (*pfnSDL_WaitSemaphoreTimeoutNS)(SDL_Semaphore *, Sint64);40typedef Uint32 (*pfnSDL_GetSemaphoreValue)(SDL_Semaphore *);41typedef void (*pfnSDL_SignalSemaphore)(SDL_Semaphore *);4243typedef struct SDL_semaphore_impl_t44{45pfnSDL_CreateSemaphore Create;46pfnSDL_DestroySemaphore Destroy;47pfnSDL_WaitSemaphoreTimeoutNS WaitTimeoutNS;48pfnSDL_GetSemaphoreValue Value;49pfnSDL_SignalSemaphore Signal;50} SDL_sem_impl_t;5152// Implementation will be chosen at runtime based on available Kernel features53static SDL_sem_impl_t SDL_sem_impl_active = { 0 };5455/**56* Atomic + WaitOnAddress implementation57*/5859// APIs not available on WinPhone 8.160// https://www.microsoft.com/en-us/download/details.aspx?id=473286162typedef BOOL(WINAPI *pfnWaitOnAddress)(volatile VOID *, PVOID, SIZE_T, DWORD);63typedef VOID(WINAPI *pfnWakeByAddressSingle)(PVOID);6465static pfnWaitOnAddress pWaitOnAddress = NULL;66static pfnWakeByAddressSingle pWakeByAddressSingle = NULL;6768typedef struct SDL_semaphore_atom69{70LONG count;71} SDL_sem_atom;7273static SDL_Semaphore *SDL_CreateSemaphore_atom(Uint32 initial_value)74{75SDL_sem_atom *sem;7677sem = (SDL_sem_atom *)SDL_malloc(sizeof(*sem));78if (sem) {79sem->count = initial_value;80}81return (SDL_Semaphore *)sem;82}8384static void SDL_DestroySemaphore_atom(SDL_Semaphore *sem)85{86SDL_free(sem);87}8889static bool SDL_WaitSemaphoreTimeoutNS_atom(SDL_Semaphore *_sem, Sint64 timeoutNS)90{91SDL_sem_atom *sem = (SDL_sem_atom *)_sem;92LONG count;93Uint64 now;94Uint64 deadline;95DWORD timeout_eff;9697if (!sem) {98return true;99}100101if (timeoutNS == 0) {102count = sem->count;103if (count == 0) {104return false;105}106107if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) {108return true;109}110111return false;112}113114if (timeoutNS < 0) {115for (;;) {116count = sem->count;117while (count == 0) {118if (!pWaitOnAddress(&sem->count, &count, sizeof(sem->count), INFINITE)) {119return false;120}121count = sem->count;122}123124if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) {125return true;126}127}128}129130/**131* WaitOnAddress is subject to spurious and stolen wakeups so we132* need to recalculate the effective timeout before every wait133*/134now = SDL_GetTicksNS();135deadline = now + timeoutNS;136137for (;;) {138count = sem->count;139// If no semaphore is available we need to wait140while (count == 0) {141now = SDL_GetTicksNS();142if (deadline > now) {143timeout_eff = (DWORD)SDL_NS_TO_MS(deadline - now);144} else {145return false;146}147if (!pWaitOnAddress(&sem->count, &count, sizeof(count), timeout_eff)) {148return false;149}150count = sem->count;151}152153// Actually the semaphore is only consumed if this succeeds154// If it doesn't we need to do everything again155if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) {156return true;157}158}159}160161static Uint32 SDL_GetSemaphoreValue_atom(SDL_Semaphore *_sem)162{163SDL_sem_atom *sem = (SDL_sem_atom *)_sem;164165if (!sem) {166return 0;167}168169return (Uint32)sem->count;170}171172static void SDL_SignalSemaphore_atom(SDL_Semaphore *_sem)173{174SDL_sem_atom *sem = (SDL_sem_atom *)_sem;175176if (!sem) {177return;178}179180InterlockedIncrement(&sem->count);181pWakeByAddressSingle(&sem->count);182}183184static const SDL_sem_impl_t SDL_sem_impl_atom = {185&SDL_CreateSemaphore_atom,186&SDL_DestroySemaphore_atom,187&SDL_WaitSemaphoreTimeoutNS_atom,188&SDL_GetSemaphoreValue_atom,189&SDL_SignalSemaphore_atom,190};191192/**193* Fallback Semaphore implementation using Kernel Semaphores194*/195196typedef struct SDL_semaphore_kern197{198HANDLE id;199LONG count;200} SDL_sem_kern;201202// Create a semaphore203static SDL_Semaphore *SDL_CreateSemaphore_kern(Uint32 initial_value)204{205SDL_sem_kern *sem;206207// Allocate sem memory208sem = (SDL_sem_kern *)SDL_malloc(sizeof(*sem));209if (sem) {210// Create the semaphore, with max value 32K211sem->id = CreateSemaphore(NULL, initial_value, 32 * 1024, NULL);212sem->count = initial_value;213if (!sem->id) {214SDL_SetError("Couldn't create semaphore");215SDL_free(sem);216sem = NULL;217}218}219return (SDL_Semaphore *)sem;220}221222// Free the semaphore223static void SDL_DestroySemaphore_kern(SDL_Semaphore *_sem)224{225SDL_sem_kern *sem = (SDL_sem_kern *)_sem;226if (sem) {227if (sem->id) {228CloseHandle(sem->id);229sem->id = 0;230}231SDL_free(sem);232}233}234235static bool SDL_WaitSemaphoreTimeoutNS_kern(SDL_Semaphore *_sem, Sint64 timeoutNS)236{237SDL_sem_kern *sem = (SDL_sem_kern *)_sem;238DWORD dwMilliseconds;239240if (!sem) {241return true;242}243244if (timeoutNS < 0) {245dwMilliseconds = INFINITE;246} else {247dwMilliseconds = (DWORD)SDL_NS_TO_MS(timeoutNS);248}249switch (WaitForSingleObjectEx(sem->id, dwMilliseconds, FALSE)) {250case WAIT_OBJECT_0:251InterlockedDecrement(&sem->count);252return true;253default:254return false;255}256}257258// Returns the current count of the semaphore259static Uint32 SDL_GetSemaphoreValue_kern(SDL_Semaphore *_sem)260{261SDL_sem_kern *sem = (SDL_sem_kern *)_sem;262if (!sem) {263return 0;264}265return (Uint32)sem->count;266}267268static void SDL_SignalSemaphore_kern(SDL_Semaphore *_sem)269{270SDL_sem_kern *sem = (SDL_sem_kern *)_sem;271272if (!sem) {273return;274}275276/* Increase the counter in the first place, because277* after a successful release the semaphore may278* immediately get destroyed by another thread which279* is waiting for this semaphore.280*/281InterlockedIncrement(&sem->count);282if (ReleaseSemaphore(sem->id, 1, NULL) == FALSE) {283InterlockedDecrement(&sem->count); // restore284}285}286287static const SDL_sem_impl_t SDL_sem_impl_kern = {288&SDL_CreateSemaphore_kern,289&SDL_DestroySemaphore_kern,290&SDL_WaitSemaphoreTimeoutNS_kern,291&SDL_GetSemaphoreValue_kern,292&SDL_SignalSemaphore_kern,293};294295/**296* Runtime selection and redirection297*/298299SDL_Semaphore *SDL_CreateSemaphore(Uint32 initial_value)300{301if (!SDL_sem_impl_active.Create) {302// Default to fallback implementation303const SDL_sem_impl_t *impl = &SDL_sem_impl_kern;304305if (!SDL_GetHintBoolean(SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL, false)) {306/* We already statically link to features from this Api307* Set (e.g. WaitForSingleObject). Dynamically loading308* API Sets is not explicitly documented but according to309* Microsoft our specific use case is legal and correct:310* https://github.com/microsoft/STL/pull/593#issuecomment-655799859311*/312HMODULE synch120 = GetModuleHandle(TEXT("api-ms-win-core-synch-l1-2-0.dll"));313if (synch120) {314// Try to load required functions provided by Win 8 or newer315pWaitOnAddress = (pfnWaitOnAddress)GetProcAddress(synch120, "WaitOnAddress");316pWakeByAddressSingle = (pfnWakeByAddressSingle)GetProcAddress(synch120, "WakeByAddressSingle");317318if (pWaitOnAddress && pWakeByAddressSingle) {319impl = &SDL_sem_impl_atom;320}321}322}323324// Copy instead of using pointer to save one level of indirection325SDL_copyp(&SDL_sem_impl_active, impl);326}327return SDL_sem_impl_active.Create(initial_value);328}329330void SDL_DestroySemaphore(SDL_Semaphore *sem)331{332SDL_sem_impl_active.Destroy(sem);333}334335bool SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS)336{337return SDL_sem_impl_active.WaitTimeoutNS(sem, timeoutNS);338}339340Uint32 SDL_GetSemaphoreValue(SDL_Semaphore *sem)341{342return SDL_sem_impl_active.Value(sem);343}344345void SDL_SignalSemaphore(SDL_Semaphore *sem)346{347SDL_sem_impl_active.Signal(sem);348}349350#endif // SDL_THREAD_WINDOWS351352353