SDL_thread.c 15 KB

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