SDL_thread.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 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. /* System independent thread management routines for SDL */
  20. #include "SDL_thread_c.h"
  21. #include "SDL_systhread.h"
  22. #include "../SDL_error_c.h"
  23. SDL_TLSID SDL_CreateTLS(void)
  24. {
  25. static SDL_AtomicInt SDL_tls_id;
  26. return (SDL_TLSID)(SDL_AtomicIncRef(&SDL_tls_id) + 1);
  27. }
  28. void *SDL_GetTLS(SDL_TLSID id)
  29. {
  30. SDL_TLSData *storage;
  31. storage = SDL_SYS_GetTLSData();
  32. if (!storage || id == 0 || id > storage->limit) {
  33. return NULL;
  34. }
  35. return storage->array[id - 1].data;
  36. }
  37. int SDL_SetTLS(SDL_TLSID id, const void *value, void(SDLCALL *destructor)(void *))
  38. {
  39. SDL_TLSData *storage;
  40. if (id == 0) {
  41. return SDL_InvalidParamError("id");
  42. }
  43. storage = SDL_SYS_GetTLSData();
  44. if (!storage || (id > storage->limit)) {
  45. unsigned int i, oldlimit, newlimit;
  46. SDL_TLSData *new_storage;
  47. oldlimit = storage ? storage->limit : 0;
  48. newlimit = (id + TLS_ALLOC_CHUNKSIZE);
  49. new_storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0]));
  50. if (!new_storage) {
  51. SDL_OutOfMemory();
  52. return -1;
  53. }
  54. storage = new_storage;
  55. storage->limit = newlimit;
  56. for (i = oldlimit; i < newlimit; ++i) {
  57. storage->array[i].data = NULL;
  58. storage->array[i].destructor = NULL;
  59. }
  60. if (SDL_SYS_SetTLSData(storage) != 0) {
  61. return -1;
  62. }
  63. }
  64. storage->array[id - 1].data = SDL_const_cast(void *, value);
  65. storage->array[id - 1].destructor = destructor;
  66. return 0;
  67. }
  68. void SDL_CleanupTLS(void)
  69. {
  70. SDL_TLSData *storage;
  71. storage = SDL_SYS_GetTLSData();
  72. if (storage) {
  73. unsigned int i;
  74. for (i = 0; i < storage->limit; ++i) {
  75. if (storage->array[i].destructor) {
  76. storage->array[i].destructor(storage->array[i].data);
  77. }
  78. }
  79. SDL_SYS_SetTLSData(NULL);
  80. SDL_free(storage);
  81. }
  82. }
  83. /* This is a generic implementation of thread-local storage which doesn't
  84. require additional OS support.
  85. It is not especially efficient and doesn't clean up thread-local storage
  86. as threads exit. If there is a real OS that doesn't support thread-local
  87. storage this implementation should be improved to be production quality.
  88. */
  89. typedef struct SDL_TLSEntry
  90. {
  91. SDL_ThreadID thread;
  92. SDL_TLSData *storage;
  93. struct SDL_TLSEntry *next;
  94. } SDL_TLSEntry;
  95. static SDL_Mutex *SDL_generic_TLS_mutex;
  96. static SDL_TLSEntry *SDL_generic_TLS;
  97. SDL_TLSData *SDL_Generic_GetTLSData(void)
  98. {
  99. SDL_ThreadID thread = SDL_GetCurrentThreadID();
  100. SDL_TLSEntry *entry;
  101. SDL_TLSData *storage = NULL;
  102. #ifndef SDL_THREADS_DISABLED
  103. if (!SDL_generic_TLS_mutex) {
  104. static SDL_SpinLock tls_lock;
  105. SDL_LockSpinlock(&tls_lock);
  106. if (!SDL_generic_TLS_mutex) {
  107. SDL_Mutex *mutex = SDL_CreateMutex();
  108. SDL_MemoryBarrierRelease();
  109. SDL_generic_TLS_mutex = mutex;
  110. if (!SDL_generic_TLS_mutex) {
  111. SDL_UnlockSpinlock(&tls_lock);
  112. return NULL;
  113. }
  114. }
  115. SDL_UnlockSpinlock(&tls_lock);
  116. }
  117. SDL_MemoryBarrierAcquire();
  118. SDL_LockMutex(SDL_generic_TLS_mutex);
  119. #endif /* SDL_THREADS_DISABLED */
  120. for (entry = SDL_generic_TLS; entry; entry = entry->next) {
  121. if (entry->thread == thread) {
  122. storage = entry->storage;
  123. break;
  124. }
  125. }
  126. #ifndef SDL_THREADS_DISABLED
  127. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  128. #endif
  129. return storage;
  130. }
  131. int SDL_Generic_SetTLSData(SDL_TLSData *data)
  132. {
  133. SDL_ThreadID thread = SDL_GetCurrentThreadID();
  134. SDL_TLSEntry *prev, *entry;
  135. /* SDL_Generic_GetTLSData() is always called first, so we can assume SDL_generic_TLS_mutex */
  136. SDL_LockMutex(SDL_generic_TLS_mutex);
  137. prev = NULL;
  138. for (entry = SDL_generic_TLS; entry; entry = entry->next) {
  139. if (entry->thread == thread) {
  140. if (data) {
  141. entry->storage = data;
  142. } else {
  143. if (prev) {
  144. prev->next = entry->next;
  145. } else {
  146. SDL_generic_TLS = entry->next;
  147. }
  148. SDL_free(entry);
  149. }
  150. break;
  151. }
  152. prev = entry;
  153. }
  154. if (!entry) {
  155. entry = (SDL_TLSEntry *)SDL_malloc(sizeof(*entry));
  156. if (entry) {
  157. entry->thread = thread;
  158. entry->storage = data;
  159. entry->next = SDL_generic_TLS;
  160. SDL_generic_TLS = entry;
  161. }
  162. }
  163. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  164. return entry ? 0 : -1;
  165. }
  166. /* Non-thread-safe global error variable */
  167. static SDL_error *SDL_GetStaticErrBuf(void)
  168. {
  169. static SDL_error SDL_global_error;
  170. static char SDL_global_error_str[128];
  171. SDL_global_error.str = SDL_global_error_str;
  172. SDL_global_error.len = sizeof(SDL_global_error_str);
  173. return &SDL_global_error;
  174. }
  175. #ifndef SDL_THREADS_DISABLED
  176. static void SDLCALL SDL_FreeErrBuf(void *data)
  177. {
  178. SDL_error *errbuf = (SDL_error *)data;
  179. if (errbuf->str) {
  180. errbuf->free_func(errbuf->str);
  181. }
  182. errbuf->free_func(errbuf);
  183. }
  184. #endif
  185. /* Routine to get the thread-specific error variable */
  186. SDL_error *SDL_GetErrBuf(SDL_bool create)
  187. {
  188. #ifdef SDL_THREADS_DISABLED
  189. return SDL_GetStaticErrBuf();
  190. #else
  191. static SDL_SpinLock tls_lock;
  192. static SDL_bool tls_being_created;
  193. static SDL_TLSID tls_errbuf;
  194. const SDL_error *ALLOCATION_IN_PROGRESS = (SDL_error *)-1;
  195. SDL_error *errbuf;
  196. if (!tls_errbuf && !create) {
  197. return NULL;
  198. }
  199. /* tls_being_created is there simply to prevent recursion if SDL_CreateTLS() fails.
  200. It also means it's possible for another thread to also use SDL_global_errbuf,
  201. but that's very unlikely and hopefully won't cause issues.
  202. */
  203. if (!tls_errbuf && !tls_being_created) {
  204. SDL_LockSpinlock(&tls_lock);
  205. if (!tls_errbuf) {
  206. SDL_TLSID slot;
  207. tls_being_created = SDL_TRUE;
  208. slot = SDL_CreateTLS();
  209. tls_being_created = SDL_FALSE;
  210. SDL_MemoryBarrierRelease();
  211. tls_errbuf = slot;
  212. }
  213. SDL_UnlockSpinlock(&tls_lock);
  214. }
  215. if (!tls_errbuf) {
  216. return SDL_GetStaticErrBuf();
  217. }
  218. SDL_MemoryBarrierAcquire();
  219. errbuf = (SDL_error *)SDL_GetTLS(tls_errbuf);
  220. if (errbuf == ALLOCATION_IN_PROGRESS) {
  221. return SDL_GetStaticErrBuf();
  222. }
  223. if (!errbuf) {
  224. /* Get the original memory functions for this allocation because the lifetime
  225. * of the error buffer may span calls to SDL_SetMemoryFunctions() by the app
  226. */
  227. SDL_realloc_func realloc_func;
  228. SDL_free_func free_func;
  229. SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);
  230. /* Mark that we're in the middle of allocating our buffer */
  231. SDL_SetTLS(tls_errbuf, ALLOCATION_IN_PROGRESS, NULL);
  232. errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));
  233. if (!errbuf) {
  234. SDL_SetTLS(tls_errbuf, NULL, NULL);
  235. return SDL_GetStaticErrBuf();
  236. }
  237. SDL_zerop(errbuf);
  238. errbuf->realloc_func = realloc_func;
  239. errbuf->free_func = free_func;
  240. SDL_SetTLS(tls_errbuf, errbuf, SDL_FreeErrBuf);
  241. }
  242. return errbuf;
  243. #endif /* SDL_THREADS_DISABLED */
  244. }
  245. void SDL_RunThread(SDL_Thread *thread)
  246. {
  247. void *userdata = thread->userdata;
  248. int(SDLCALL * userfunc)(void *) = thread->userfunc;
  249. int *statusloc = &thread->status;
  250. /* Perform any system-dependent setup - this function may not fail */
  251. SDL_SYS_SetupThread(thread->name);
  252. /* Get the thread id */
  253. thread->threadid = SDL_GetCurrentThreadID();
  254. /* Run the function */
  255. *statusloc = userfunc(userdata);
  256. /* Clean up thread-local storage */
  257. SDL_CleanupTLS();
  258. /* Mark us as ready to be joined (or detached) */
  259. if (!SDL_AtomicCompareAndSwap(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_ZOMBIE)) {
  260. /* Clean up if something already detached us. */
  261. if (SDL_AtomicCompareAndSwap(&thread->state, SDL_THREAD_STATE_DETACHED, SDL_THREAD_STATE_CLEANED)) {
  262. if (thread->name) {
  263. SDL_free(thread->name);
  264. }
  265. SDL_free(thread);
  266. }
  267. }
  268. }
  269. #ifdef SDL_CreateThread
  270. #undef SDL_CreateThread
  271. #undef SDL_CreateThreadWithStackSize
  272. #endif
  273. #if SDL_DYNAMIC_API
  274. #define SDL_CreateThread SDL_CreateThread_REAL
  275. #define SDL_CreateThreadWithStackSize SDL_CreateThreadWithStackSize_REAL
  276. #endif
  277. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  278. SDL_Thread *SDL_CreateThreadWithStackSize(int(SDLCALL *fn)(void *),
  279. const char *name, const size_t stacksize, void *data,
  280. pfnSDL_CurrentBeginThread pfnBeginThread,
  281. pfnSDL_CurrentEndThread pfnEndThread)
  282. #else
  283. SDL_Thread *SDL_CreateThreadWithStackSize(int(SDLCALL *fn)(void *),
  284. const char *name, const size_t stacksize, void *data)
  285. #endif
  286. {
  287. SDL_Thread *thread;
  288. int ret;
  289. /* Allocate memory for the thread info structure */
  290. thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread));
  291. if (!thread) {
  292. return NULL;
  293. }
  294. thread->status = -1;
  295. SDL_AtomicSet(&thread->state, SDL_THREAD_STATE_ALIVE);
  296. /* Set up the arguments for the thread */
  297. if (name) {
  298. thread->name = SDL_strdup(name);
  299. if (!thread->name) {
  300. SDL_free(thread);
  301. return NULL;
  302. }
  303. }
  304. thread->userfunc = fn;
  305. thread->userdata = data;
  306. thread->stacksize = stacksize;
  307. /* Create the thread and go! */
  308. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  309. ret = SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread);
  310. #else
  311. ret = SDL_SYS_CreateThread(thread);
  312. #endif
  313. if (ret < 0) {
  314. /* Oops, failed. Gotta free everything */
  315. SDL_free(thread->name);
  316. SDL_free(thread);
  317. thread = NULL;
  318. }
  319. /* Everything is running now */
  320. return thread;
  321. }
  322. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  323. DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(int(SDLCALL *fn)(void *),
  324. const char *name, void *data,
  325. pfnSDL_CurrentBeginThread pfnBeginThread,
  326. pfnSDL_CurrentEndThread pfnEndThread)
  327. #else
  328. DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(int(SDLCALL *fn)(void *),
  329. const char *name, void *data)
  330. #endif
  331. {
  332. /* !!! FIXME: in 2.1, just make stackhint part of the usual API. */
  333. const char *stackhint = SDL_GetHint(SDL_HINT_THREAD_STACK_SIZE);
  334. size_t stacksize = 0;
  335. /* If the SDL_HINT_THREAD_STACK_SIZE exists, use it */
  336. if (stackhint) {
  337. char *endp = NULL;
  338. const Sint64 hintval = SDL_strtoll(stackhint, &endp, 10);
  339. if ((*stackhint != '\0') && (*endp == '\0')) { /* a valid number? */
  340. if (hintval > 0) { /* reject bogus values. */
  341. stacksize = (size_t)hintval;
  342. }
  343. }
  344. }
  345. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  346. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, pfnBeginThread, pfnEndThread);
  347. #else
  348. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  349. #endif
  350. }
  351. SDL_Thread *SDL_CreateThreadInternal(int(SDLCALL *fn)(void *), const char *name,
  352. const size_t stacksize, void *data)
  353. {
  354. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  355. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, NULL, NULL);
  356. #else
  357. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  358. #endif
  359. }
  360. SDL_ThreadID SDL_GetThreadID(SDL_Thread *thread)
  361. {
  362. SDL_ThreadID id;
  363. if (thread) {
  364. id = thread->threadid;
  365. } else {
  366. id = SDL_GetCurrentThreadID();
  367. }
  368. return id;
  369. }
  370. const char *SDL_GetThreadName(SDL_Thread *thread)
  371. {
  372. if (thread) {
  373. return thread->name;
  374. } else {
  375. return NULL;
  376. }
  377. }
  378. int SDL_SetThreadPriority(SDL_ThreadPriority priority)
  379. {
  380. return SDL_SYS_SetThreadPriority(priority);
  381. }
  382. void SDL_WaitThread(SDL_Thread *thread, int *status)
  383. {
  384. if (thread) {
  385. SDL_SYS_WaitThread(thread);
  386. if (status) {
  387. *status = thread->status;
  388. }
  389. if (thread->name) {
  390. SDL_free(thread->name);
  391. }
  392. SDL_free(thread);
  393. }
  394. }
  395. void SDL_DetachThread(SDL_Thread *thread)
  396. {
  397. if (!thread) {
  398. return;
  399. }
  400. /* Grab dibs if the state is alive+joinable. */
  401. if (SDL_AtomicCompareAndSwap(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_DETACHED)) {
  402. SDL_SYS_DetachThread(thread);
  403. } else {
  404. /* all other states are pretty final, see where we landed. */
  405. const int thread_state = SDL_AtomicGet(&thread->state);
  406. if ((thread_state == SDL_THREAD_STATE_DETACHED) || (thread_state == SDL_THREAD_STATE_CLEANED)) {
  407. return; /* already detached (you shouldn't call this twice!) */
  408. } else if (thread_state == SDL_THREAD_STATE_ZOMBIE) {
  409. SDL_WaitThread(thread, NULL); /* already done, clean it up. */
  410. } else {
  411. SDL_assert(0 && "Unexpected thread state");
  412. }
  413. }
  414. }
  415. int SDL_WaitSemaphore(SDL_Semaphore *sem)
  416. {
  417. return SDL_WaitSemaphoreTimeoutNS(sem, -1);
  418. }
  419. int SDL_TryWaitSemaphore(SDL_Semaphore *sem)
  420. {
  421. return SDL_WaitSemaphoreTimeoutNS(sem, 0);
  422. }
  423. int SDL_WaitSemaphoreTimeout(SDL_Semaphore *sem, Sint32 timeoutMS)
  424. {
  425. Sint64 timeoutNS;
  426. if (timeoutMS >= 0) {
  427. timeoutNS = SDL_MS_TO_NS(timeoutMS);
  428. } else {
  429. timeoutNS = -1;
  430. }
  431. return SDL_WaitSemaphoreTimeoutNS(sem, timeoutNS);
  432. }
  433. int SDL_WaitCondition(SDL_Condition *cond, SDL_Mutex *mutex)
  434. {
  435. return SDL_WaitConditionTimeoutNS(cond, mutex, -1);
  436. }
  437. int SDL_WaitConditionTimeout(SDL_Condition *cond, SDL_Mutex *mutex, Sint32 timeoutMS)
  438. {
  439. Sint64 timeoutNS;
  440. if (timeoutMS >= 0) {
  441. timeoutNS = SDL_MS_TO_NS(timeoutMS);
  442. } else {
  443. timeoutNS = -1;
  444. }
  445. return SDL_WaitConditionTimeoutNS(cond, mutex, timeoutNS);
  446. }