SDL_thread.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <[email protected]>
  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 == NULL || 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 == NULL || (id > storage->limit)) {
  45. unsigned int i, oldlimit, newlimit;
  46. oldlimit = storage ? storage->limit : 0;
  47. newlimit = (id + TLS_ALLOC_CHUNKSIZE);
  48. storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0]));
  49. if (storage == NULL) {
  50. return SDL_OutOfMemory();
  51. }
  52. storage->limit = newlimit;
  53. for (i = oldlimit; i < newlimit; ++i) {
  54. storage->array[i].data = NULL;
  55. storage->array[i].destructor = NULL;
  56. }
  57. if (SDL_SYS_SetTLSData(storage) != 0) {
  58. return -1;
  59. }
  60. }
  61. storage->array[id - 1].data = SDL_const_cast(void *, value);
  62. storage->array[id - 1].destructor = destructor;
  63. return 0;
  64. }
  65. void SDL_CleanupTLS(void)
  66. {
  67. SDL_TLSData *storage;
  68. storage = SDL_SYS_GetTLSData();
  69. if (storage) {
  70. unsigned int i;
  71. for (i = 0; i < storage->limit; ++i) {
  72. if (storage->array[i].destructor) {
  73. storage->array[i].destructor(storage->array[i].data);
  74. }
  75. }
  76. SDL_SYS_SetTLSData(NULL);
  77. SDL_free(storage);
  78. }
  79. }
  80. /* This is a generic implementation of thread-local storage which doesn't
  81. require additional OS support.
  82. It is not especially efficient and doesn't clean up thread-local storage
  83. as threads exit. If there is a real OS that doesn't support thread-local
  84. storage this implementation should be improved to be production quality.
  85. */
  86. typedef struct SDL_TLSEntry
  87. {
  88. SDL_threadID thread;
  89. SDL_TLSData *storage;
  90. struct SDL_TLSEntry *next;
  91. } SDL_TLSEntry;
  92. static SDL_Mutex *SDL_generic_TLS_mutex;
  93. static SDL_TLSEntry *SDL_generic_TLS;
  94. SDL_TLSData *SDL_Generic_GetTLSData(void)
  95. {
  96. SDL_threadID thread = SDL_ThreadID();
  97. SDL_TLSEntry *entry;
  98. SDL_TLSData *storage = NULL;
  99. #ifndef SDL_THREADS_DISABLED
  100. if (SDL_generic_TLS_mutex == NULL) {
  101. static SDL_SpinLock tls_lock;
  102. SDL_AtomicLock(&tls_lock);
  103. if (SDL_generic_TLS_mutex == NULL) {
  104. SDL_Mutex *mutex = SDL_CreateMutex();
  105. SDL_MemoryBarrierRelease();
  106. SDL_generic_TLS_mutex = mutex;
  107. if (SDL_generic_TLS_mutex == NULL) {
  108. SDL_AtomicUnlock(&tls_lock);
  109. return NULL;
  110. }
  111. }
  112. SDL_AtomicUnlock(&tls_lock);
  113. }
  114. SDL_MemoryBarrierAcquire();
  115. SDL_LockMutex(SDL_generic_TLS_mutex);
  116. #endif /* SDL_THREADS_DISABLED */
  117. for (entry = SDL_generic_TLS; entry; entry = entry->next) {
  118. if (entry->thread == thread) {
  119. storage = entry->storage;
  120. break;
  121. }
  122. }
  123. #ifndef SDL_THREADS_DISABLED
  124. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  125. #endif
  126. return storage;
  127. }
  128. int SDL_Generic_SetTLSData(SDL_TLSData *data)
  129. {
  130. SDL_threadID thread = SDL_ThreadID();
  131. SDL_TLSEntry *prev, *entry;
  132. /* SDL_Generic_GetTLSData() is always called first, so we can assume SDL_generic_TLS_mutex */
  133. SDL_LockMutex(SDL_generic_TLS_mutex);
  134. prev = NULL;
  135. for (entry = SDL_generic_TLS; entry; entry = entry->next) {
  136. if (entry->thread == thread) {
  137. if (data != NULL) {
  138. entry->storage = data;
  139. } else {
  140. if (prev != NULL) {
  141. prev->next = entry->next;
  142. } else {
  143. SDL_generic_TLS = entry->next;
  144. }
  145. SDL_free(entry);
  146. }
  147. break;
  148. }
  149. prev = entry;
  150. }
  151. if (entry == NULL) {
  152. entry = (SDL_TLSEntry *)SDL_malloc(sizeof(*entry));
  153. if (entry) {
  154. entry->thread = thread;
  155. entry->storage = data;
  156. entry->next = SDL_generic_TLS;
  157. SDL_generic_TLS = entry;
  158. }
  159. }
  160. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  161. if (entry == NULL) {
  162. return SDL_OutOfMemory();
  163. }
  164. return 0;
  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(void)
  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. /* tls_being_created is there simply to prevent recursion if SDL_CreateTLS() fails.
  197. It also means it's possible for another thread to also use SDL_global_errbuf,
  198. but that's very unlikely and hopefully won't cause issues.
  199. */
  200. if (!tls_errbuf && !tls_being_created) {
  201. SDL_AtomicLock(&tls_lock);
  202. if (!tls_errbuf) {
  203. SDL_TLSID slot;
  204. tls_being_created = SDL_TRUE;
  205. slot = SDL_CreateTLS();
  206. tls_being_created = SDL_FALSE;
  207. SDL_MemoryBarrierRelease();
  208. tls_errbuf = slot;
  209. }
  210. SDL_AtomicUnlock(&tls_lock);
  211. }
  212. if (!tls_errbuf) {
  213. return SDL_GetStaticErrBuf();
  214. }
  215. SDL_MemoryBarrierAcquire();
  216. errbuf = (SDL_error *)SDL_GetTLS(tls_errbuf);
  217. if (errbuf == ALLOCATION_IN_PROGRESS) {
  218. return SDL_GetStaticErrBuf();
  219. }
  220. if (errbuf == NULL) {
  221. /* Get the original memory functions for this allocation because the lifetime
  222. * of the error buffer may span calls to SDL_SetMemoryFunctions() by the app
  223. */
  224. SDL_realloc_func realloc_func;
  225. SDL_free_func free_func;
  226. SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);
  227. /* Mark that we're in the middle of allocating our buffer */
  228. SDL_SetTLS(tls_errbuf, ALLOCATION_IN_PROGRESS, NULL);
  229. errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));
  230. if (errbuf == NULL) {
  231. SDL_SetTLS(tls_errbuf, NULL, NULL);
  232. return SDL_GetStaticErrBuf();
  233. }
  234. SDL_zerop(errbuf);
  235. errbuf->realloc_func = realloc_func;
  236. errbuf->free_func = free_func;
  237. SDL_SetTLS(tls_errbuf, errbuf, SDL_FreeErrBuf);
  238. }
  239. return errbuf;
  240. #endif /* SDL_THREADS_DISABLED */
  241. }
  242. void SDL_RunThread(SDL_Thread *thread)
  243. {
  244. void *userdata = thread->userdata;
  245. int(SDLCALL * userfunc)(void *) = thread->userfunc;
  246. int *statusloc = &thread->status;
  247. /* Perform any system-dependent setup - this function may not fail */
  248. SDL_SYS_SetupThread(thread->name);
  249. /* Get the thread id */
  250. thread->threadid = SDL_ThreadID();
  251. /* Run the function */
  252. *statusloc = userfunc(userdata);
  253. /* Clean up thread-local storage */
  254. SDL_CleanupTLS();
  255. /* Mark us as ready to be joined (or detached) */
  256. if (!SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_ZOMBIE)) {
  257. /* Clean up if something already detached us. */
  258. if (SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_DETACHED, SDL_THREAD_STATE_CLEANED)) {
  259. if (thread->name) {
  260. SDL_free(thread->name);
  261. }
  262. SDL_free(thread);
  263. }
  264. }
  265. }
  266. #ifdef SDL_CreateThread
  267. #undef SDL_CreateThread
  268. #undef SDL_CreateThreadWithStackSize
  269. #endif
  270. #if SDL_DYNAMIC_API
  271. #define SDL_CreateThread SDL_CreateThread_REAL
  272. #define SDL_CreateThreadWithStackSize SDL_CreateThreadWithStackSize_REAL
  273. #endif
  274. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  275. SDL_Thread *SDL_CreateThreadWithStackSize(int(SDLCALL *fn)(void *),
  276. const char *name, const size_t stacksize, void *data,
  277. pfnSDL_CurrentBeginThread pfnBeginThread,
  278. pfnSDL_CurrentEndThread pfnEndThread)
  279. #else
  280. SDL_Thread *SDL_CreateThreadWithStackSize(int(SDLCALL *fn)(void *),
  281. const char *name, const size_t stacksize, void *data)
  282. #endif
  283. {
  284. SDL_Thread *thread;
  285. int ret;
  286. /* Allocate memory for the thread info structure */
  287. thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread));
  288. if (thread == NULL) {
  289. SDL_OutOfMemory();
  290. return NULL;
  291. }
  292. thread->status = -1;
  293. SDL_AtomicSet(&thread->state, SDL_THREAD_STATE_ALIVE);
  294. /* Set up the arguments for the thread */
  295. if (name != NULL) {
  296. thread->name = SDL_strdup(name);
  297. if (thread->name == NULL) {
  298. SDL_OutOfMemory();
  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 != NULL) {
  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_ThreadID();
  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 == NULL) {
  397. return;
  398. }
  399. /* Grab dibs if the state is alive+joinable. */
  400. if (SDL_AtomicCAS(&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, SDL_MUTEX_MAXWAIT);
  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, SDL_MUTEX_MAXWAIT);
  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. }