SDL_syssem.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_THREAD_WINDOWS
  20. /**
  21. * Semaphore functions using the Win32 API
  22. * There are two implementations available based on:
  23. * - Kernel Semaphores. Available on all OS versions. (kern)
  24. * Heavy-weight inter-process kernel objects.
  25. * - Atomics and WaitOnAddress API. (atom)
  26. * Faster due to significantly less context switches.
  27. * Requires Windows 8 or newer.
  28. * which are chosen at runtime.
  29. */
  30. #include "../../core/windows/SDL_windows.h"
  31. typedef SDL_Semaphore *(*pfnSDL_CreateSemaphore)(Uint32);
  32. typedef void (*pfnSDL_DestroySemaphore)(SDL_Semaphore *);
  33. typedef bool (*pfnSDL_WaitSemaphoreTimeoutNS)(SDL_Semaphore *, Sint64);
  34. typedef Uint32 (*pfnSDL_GetSemaphoreValue)(SDL_Semaphore *);
  35. typedef void (*pfnSDL_SignalSemaphore)(SDL_Semaphore *);
  36. typedef struct SDL_semaphore_impl_t
  37. {
  38. pfnSDL_CreateSemaphore Create;
  39. pfnSDL_DestroySemaphore Destroy;
  40. pfnSDL_WaitSemaphoreTimeoutNS WaitTimeoutNS;
  41. pfnSDL_GetSemaphoreValue Value;
  42. pfnSDL_SignalSemaphore Signal;
  43. } SDL_sem_impl_t;
  44. // Implementation will be chosen at runtime based on available Kernel features
  45. static SDL_sem_impl_t SDL_sem_impl_active = { 0 };
  46. /**
  47. * Atomic + WaitOnAddress implementation
  48. */
  49. // APIs not available on WinPhone 8.1
  50. // https://www.microsoft.com/en-us/download/details.aspx?id=47328
  51. typedef BOOL (WINAPI *pfnWaitOnAddress)(volatile VOID *, PVOID, SIZE_T, DWORD);
  52. typedef VOID (WINAPI *pfnWakeByAddressSingle)(PVOID);
  53. static pfnWaitOnAddress pWaitOnAddress = NULL;
  54. static pfnWakeByAddressSingle pWakeByAddressSingle = NULL;
  55. typedef struct SDL_semaphore_atom
  56. {
  57. LONG count;
  58. } SDL_sem_atom;
  59. static SDL_Semaphore *SDL_CreateSemaphore_atom(Uint32 initial_value)
  60. {
  61. SDL_sem_atom *sem;
  62. sem = (SDL_sem_atom *)SDL_malloc(sizeof(*sem));
  63. if (sem) {
  64. sem->count = initial_value;
  65. }
  66. return (SDL_Semaphore *)sem;
  67. }
  68. static void SDL_DestroySemaphore_atom(SDL_Semaphore *sem)
  69. {
  70. SDL_free(sem);
  71. }
  72. static bool SDL_WaitSemaphoreTimeoutNS_atom(SDL_Semaphore *_sem, Sint64 timeoutNS)
  73. {
  74. SDL_sem_atom *sem = (SDL_sem_atom *)_sem;
  75. LONG count;
  76. Uint64 now;
  77. Uint64 deadline;
  78. DWORD timeout_eff;
  79. if (!sem) {
  80. return true;
  81. }
  82. if (timeoutNS == 0) {
  83. count = sem->count;
  84. if (count == 0) {
  85. return false;
  86. }
  87. if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) {
  88. return true;
  89. }
  90. return false;
  91. }
  92. if (timeoutNS < 0) {
  93. for (;;) {
  94. count = sem->count;
  95. while (count == 0) {
  96. if (!pWaitOnAddress(&sem->count, &count, sizeof(sem->count), INFINITE)) {
  97. return false;
  98. }
  99. count = sem->count;
  100. }
  101. if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) {
  102. return true;
  103. }
  104. }
  105. }
  106. /**
  107. * WaitOnAddress is subject to spurious and stolen wakeups so we
  108. * need to recalculate the effective timeout before every wait
  109. */
  110. now = SDL_GetTicksNS();
  111. deadline = now + timeoutNS;
  112. for (;;) {
  113. count = sem->count;
  114. // If no semaphore is available we need to wait
  115. while (count == 0) {
  116. now = SDL_GetTicksNS();
  117. if (deadline > now) {
  118. timeout_eff = (DWORD)SDL_NS_TO_MS(deadline - now);
  119. } else {
  120. return false;
  121. }
  122. if (!pWaitOnAddress(&sem->count, &count, sizeof(count), timeout_eff)) {
  123. return false;
  124. }
  125. count = sem->count;
  126. }
  127. // Actually the semaphore is only consumed if this succeeds
  128. // If it doesn't we need to do everything again
  129. if (InterlockedCompareExchange(&sem->count, count - 1, count) == count) {
  130. return true;
  131. }
  132. }
  133. }
  134. static Uint32 SDL_GetSemaphoreValue_atom(SDL_Semaphore *_sem)
  135. {
  136. SDL_sem_atom *sem = (SDL_sem_atom *)_sem;
  137. if (!sem) {
  138. return 0;
  139. }
  140. return (Uint32)sem->count;
  141. }
  142. static void SDL_SignalSemaphore_atom(SDL_Semaphore *_sem)
  143. {
  144. SDL_sem_atom *sem = (SDL_sem_atom *)_sem;
  145. if (!sem) {
  146. return;
  147. }
  148. InterlockedIncrement(&sem->count);
  149. pWakeByAddressSingle(&sem->count);
  150. }
  151. static const SDL_sem_impl_t SDL_sem_impl_atom = {
  152. &SDL_CreateSemaphore_atom,
  153. &SDL_DestroySemaphore_atom,
  154. &SDL_WaitSemaphoreTimeoutNS_atom,
  155. &SDL_GetSemaphoreValue_atom,
  156. &SDL_SignalSemaphore_atom,
  157. };
  158. /**
  159. * Fallback Semaphore implementation using Kernel Semaphores
  160. */
  161. typedef struct SDL_semaphore_kern
  162. {
  163. HANDLE id;
  164. LONG count;
  165. } SDL_sem_kern;
  166. // Create a semaphore
  167. static SDL_Semaphore *SDL_CreateSemaphore_kern(Uint32 initial_value)
  168. {
  169. SDL_sem_kern *sem;
  170. // Allocate sem memory
  171. sem = (SDL_sem_kern *)SDL_malloc(sizeof(*sem));
  172. if (sem) {
  173. // Create the semaphore, with max value 32K
  174. sem->id = CreateSemaphore(NULL, initial_value, 32 * 1024, NULL);
  175. sem->count = initial_value;
  176. if (!sem->id) {
  177. SDL_SetError("Couldn't create semaphore");
  178. SDL_free(sem);
  179. sem = NULL;
  180. }
  181. }
  182. return (SDL_Semaphore *)sem;
  183. }
  184. // Free the semaphore
  185. static void SDL_DestroySemaphore_kern(SDL_Semaphore *_sem)
  186. {
  187. SDL_sem_kern *sem = (SDL_sem_kern *)_sem;
  188. if (sem) {
  189. if (sem->id) {
  190. CloseHandle(sem->id);
  191. sem->id = 0;
  192. }
  193. SDL_free(sem);
  194. }
  195. }
  196. static bool SDL_WaitSemaphoreTimeoutNS_kern(SDL_Semaphore *_sem, Sint64 timeoutNS)
  197. {
  198. SDL_sem_kern *sem = (SDL_sem_kern *)_sem;
  199. DWORD dwMilliseconds;
  200. if (!sem) {
  201. return true;
  202. }
  203. if (timeoutNS < 0) {
  204. dwMilliseconds = INFINITE;
  205. } else {
  206. dwMilliseconds = (DWORD)SDL_NS_TO_MS(timeoutNS);
  207. }
  208. switch (WaitForSingleObjectEx(sem->id, dwMilliseconds, FALSE)) {
  209. case WAIT_OBJECT_0:
  210. InterlockedDecrement(&sem->count);
  211. return true;
  212. default:
  213. return false;
  214. }
  215. }
  216. // Returns the current count of the semaphore
  217. static Uint32 SDL_GetSemaphoreValue_kern(SDL_Semaphore *_sem)
  218. {
  219. SDL_sem_kern *sem = (SDL_sem_kern *)_sem;
  220. if (!sem) {
  221. return 0;
  222. }
  223. return (Uint32)sem->count;
  224. }
  225. static void SDL_SignalSemaphore_kern(SDL_Semaphore *_sem)
  226. {
  227. SDL_sem_kern *sem = (SDL_sem_kern *)_sem;
  228. if (!sem) {
  229. return;
  230. }
  231. /* Increase the counter in the first place, because
  232. * after a successful release the semaphore may
  233. * immediately get destroyed by another thread which
  234. * is waiting for this semaphore.
  235. */
  236. InterlockedIncrement(&sem->count);
  237. if (ReleaseSemaphore(sem->id, 1, NULL) == FALSE) {
  238. InterlockedDecrement(&sem->count); // restore
  239. }
  240. }
  241. static const SDL_sem_impl_t SDL_sem_impl_kern = {
  242. &SDL_CreateSemaphore_kern,
  243. &SDL_DestroySemaphore_kern,
  244. &SDL_WaitSemaphoreTimeoutNS_kern,
  245. &SDL_GetSemaphoreValue_kern,
  246. &SDL_SignalSemaphore_kern,
  247. };
  248. /**
  249. * Runtime selection and redirection
  250. */
  251. SDL_Semaphore *SDL_CreateSemaphore(Uint32 initial_value)
  252. {
  253. if (!SDL_sem_impl_active.Create) {
  254. // Default to fallback implementation
  255. const SDL_sem_impl_t *impl = &SDL_sem_impl_kern;
  256. if (!SDL_GetHintBoolean(SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL, false)) {
  257. /* We already statically link to features from this Api
  258. * Set (e.g. WaitForSingleObject). Dynamically loading
  259. * API Sets is not explicitly documented but according to
  260. * Microsoft our specific use case is legal and correct:
  261. * https://github.com/microsoft/STL/pull/593#issuecomment-655799859
  262. */
  263. HMODULE synch120 = GetModuleHandle(TEXT("api-ms-win-core-synch-l1-2-0.dll"));
  264. if (synch120) {
  265. // Try to load required functions provided by Win 8 or newer
  266. pWaitOnAddress = (pfnWaitOnAddress)GetProcAddress(synch120, "WaitOnAddress");
  267. pWakeByAddressSingle = (pfnWakeByAddressSingle)GetProcAddress(synch120, "WakeByAddressSingle");
  268. if (pWaitOnAddress && pWakeByAddressSingle) {
  269. impl = &SDL_sem_impl_atom;
  270. }
  271. }
  272. }
  273. // Copy instead of using pointer to save one level of indirection
  274. SDL_copyp(&SDL_sem_impl_active, impl);
  275. }
  276. return SDL_sem_impl_active.Create(initial_value);
  277. }
  278. void SDL_DestroySemaphore(SDL_Semaphore *sem)
  279. {
  280. SDL_sem_impl_active.Destroy(sem);
  281. }
  282. bool SDL_WaitSemaphoreTimeoutNS(SDL_Semaphore *sem, Sint64 timeoutNS)
  283. {
  284. return SDL_sem_impl_active.WaitTimeoutNS(sem, timeoutNS);
  285. }
  286. Uint32 SDL_GetSemaphoreValue(SDL_Semaphore *sem)
  287. {
  288. return SDL_sem_impl_active.Value(sem);
  289. }
  290. void SDL_SignalSemaphore(SDL_Semaphore *sem)
  291. {
  292. SDL_sem_impl_active.Signal(sem);
  293. }
  294. #endif // SDL_THREAD_WINDOWS