SDL_thread.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 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
  24. SDL_TLSCreate()
  25. {
  26. static SDL_atomic_t SDL_tls_id;
  27. return SDL_AtomicIncRef(&SDL_tls_id) + 1;
  28. }
  29. void *
  30. SDL_TLSGet(SDL_TLSID id)
  31. {
  32. SDL_TLSData *storage;
  33. storage = SDL_SYS_GetTLSData();
  34. if (storage == NULL || id == 0 || id > storage->limit) {
  35. return NULL;
  36. }
  37. return storage->array[id - 1].data;
  38. }
  39. int SDL_TLSSet(SDL_TLSID id, const void *value, void(SDLCALL *destructor)(void *))
  40. {
  41. SDL_TLSData *storage;
  42. if (id == 0) {
  43. return SDL_InvalidParamError("id");
  44. }
  45. storage = SDL_SYS_GetTLSData();
  46. if (storage == NULL || (id > storage->limit)) {
  47. unsigned int i, oldlimit, newlimit;
  48. oldlimit = storage ? storage->limit : 0;
  49. newlimit = (id + TLS_ALLOC_CHUNKSIZE);
  50. storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0]));
  51. if (storage == NULL) {
  52. return SDL_OutOfMemory();
  53. }
  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_TLSCleanup()
  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 *
  97. SDL_Generic_GetTLSData(void)
  98. {
  99. SDL_threadID thread = SDL_ThreadID();
  100. SDL_TLSEntry *entry;
  101. SDL_TLSData *storage = NULL;
  102. #if !SDL_THREADS_DISABLED
  103. if (SDL_generic_TLS_mutex == NULL) {
  104. static SDL_SpinLock tls_lock;
  105. SDL_AtomicLock(&tls_lock);
  106. if (SDL_generic_TLS_mutex == NULL) {
  107. SDL_mutex *mutex = SDL_CreateMutex();
  108. SDL_MemoryBarrierRelease();
  109. SDL_generic_TLS_mutex = mutex;
  110. if (SDL_generic_TLS_mutex == NULL) {
  111. SDL_AtomicUnlock(&tls_lock);
  112. return NULL;
  113. }
  114. }
  115. SDL_AtomicUnlock(&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. #if !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_ThreadID();
  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 != NULL) {
  141. entry->storage = data;
  142. } else {
  143. if (prev != NULL) {
  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 == NULL) {
  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. if (entry == NULL) {
  165. return SDL_OutOfMemory();
  166. }
  167. return 0;
  168. }
  169. /* Non-thread-safe global error variable */
  170. static SDL_error *SDL_GetStaticErrBuf()
  171. {
  172. static SDL_error SDL_global_error;
  173. static char SDL_global_error_str[128];
  174. SDL_global_error.str = SDL_global_error_str;
  175. SDL_global_error.len = sizeof(SDL_global_error_str);
  176. return &SDL_global_error;
  177. }
  178. #if !SDL_THREADS_DISABLED
  179. static void SDLCALL SDL_FreeErrBuf(void *data)
  180. {
  181. SDL_error *errbuf = (SDL_error *)data;
  182. if (errbuf->str) {
  183. errbuf->free_func(errbuf->str);
  184. }
  185. errbuf->free_func(errbuf);
  186. }
  187. #endif
  188. /* Routine to get the thread-specific error variable */
  189. SDL_error *
  190. SDL_GetErrBuf(void)
  191. {
  192. #if SDL_THREADS_DISABLED
  193. return SDL_GetStaticErrBuf();
  194. #else
  195. static SDL_SpinLock tls_lock;
  196. static SDL_bool tls_being_created;
  197. static SDL_TLSID tls_errbuf;
  198. const SDL_error *ALLOCATION_IN_PROGRESS = (SDL_error *)-1;
  199. SDL_error *errbuf;
  200. /* tls_being_created is there simply to prevent recursion if SDL_TLSCreate() fails.
  201. It also means it's possible for another thread to also use SDL_global_errbuf,
  202. but that's very unlikely and hopefully won't cause issues.
  203. */
  204. if (!tls_errbuf && !tls_being_created) {
  205. SDL_AtomicLock(&tls_lock);
  206. if (!tls_errbuf) {
  207. SDL_TLSID slot;
  208. tls_being_created = SDL_TRUE;
  209. slot = SDL_TLSCreate();
  210. tls_being_created = SDL_FALSE;
  211. SDL_MemoryBarrierRelease();
  212. tls_errbuf = slot;
  213. }
  214. SDL_AtomicUnlock(&tls_lock);
  215. }
  216. if (!tls_errbuf) {
  217. return SDL_GetStaticErrBuf();
  218. }
  219. SDL_MemoryBarrierAcquire();
  220. errbuf = (SDL_error *)SDL_TLSGet(tls_errbuf);
  221. if (errbuf == ALLOCATION_IN_PROGRESS) {
  222. return SDL_GetStaticErrBuf();
  223. }
  224. if (errbuf == NULL) {
  225. /* Get the original memory functions for this allocation because the lifetime
  226. * of the error buffer may span calls to SDL_SetMemoryFunctions() by the app
  227. */
  228. SDL_realloc_func realloc_func;
  229. SDL_free_func free_func;
  230. SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);
  231. /* Mark that we're in the middle of allocating our buffer */
  232. SDL_TLSSet(tls_errbuf, ALLOCATION_IN_PROGRESS, NULL);
  233. errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));
  234. if (errbuf == NULL) {
  235. SDL_TLSSet(tls_errbuf, NULL, NULL);
  236. return SDL_GetStaticErrBuf();
  237. }
  238. SDL_zerop(errbuf);
  239. errbuf->realloc_func = realloc_func;
  240. errbuf->free_func = free_func;
  241. SDL_TLSSet(tls_errbuf, errbuf, SDL_FreeErrBuf);
  242. }
  243. return errbuf;
  244. #endif /* SDL_THREADS_DISABLED */
  245. }
  246. void SDL_RunThread(SDL_Thread *thread)
  247. {
  248. void *userdata = thread->userdata;
  249. int(SDLCALL * userfunc)(void *) = thread->userfunc;
  250. int *statusloc = &thread->status;
  251. /* Perform any system-dependent setup - this function may not fail */
  252. SDL_SYS_SetupThread(thread->name);
  253. /* Get the thread id */
  254. thread->threadid = SDL_ThreadID();
  255. /* Run the function */
  256. *statusloc = userfunc(userdata);
  257. /* Clean up thread-local storage */
  258. SDL_TLSCleanup();
  259. /* Mark us as ready to be joined (or detached) */
  260. if (!SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_ZOMBIE)) {
  261. /* Clean up if something already detached us. */
  262. if (SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_DETACHED, SDL_THREAD_STATE_CLEANED)) {
  263. if (thread->name) {
  264. SDL_free(thread->name);
  265. }
  266. SDL_free(thread);
  267. }
  268. }
  269. }
  270. #ifdef SDL_CreateThread
  271. #undef SDL_CreateThread
  272. #undef SDL_CreateThreadWithStackSize
  273. #endif
  274. #if SDL_DYNAMIC_API
  275. #define SDL_CreateThread SDL_CreateThread_REAL
  276. #define SDL_CreateThreadWithStackSize SDL_CreateThreadWithStackSize_REAL
  277. #endif
  278. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  279. SDL_Thread *
  280. SDL_CreateThreadWithStackSize(int(SDLCALL *fn)(void *),
  281. const char *name, const size_t stacksize, void *data,
  282. pfnSDL_CurrentBeginThread pfnBeginThread,
  283. pfnSDL_CurrentEndThread pfnEndThread)
  284. #else
  285. SDL_Thread *
  286. SDL_CreateThreadWithStackSize(int(SDLCALL *fn)(void *),
  287. const char *name, const size_t stacksize, void *data)
  288. #endif
  289. {
  290. SDL_Thread *thread;
  291. int ret;
  292. /* Allocate memory for the thread info structure */
  293. thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread));
  294. if (thread == NULL) {
  295. SDL_OutOfMemory();
  296. return NULL;
  297. }
  298. thread->status = -1;
  299. SDL_AtomicSet(&thread->state, SDL_THREAD_STATE_ALIVE);
  300. /* Set up the arguments for the thread */
  301. if (name != NULL) {
  302. thread->name = SDL_strdup(name);
  303. if (thread->name == NULL) {
  304. SDL_OutOfMemory();
  305. SDL_free(thread);
  306. return NULL;
  307. }
  308. }
  309. thread->userfunc = fn;
  310. thread->userdata = data;
  311. thread->stacksize = stacksize;
  312. /* Create the thread and go! */
  313. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  314. ret = SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread);
  315. #else
  316. ret = SDL_SYS_CreateThread(thread);
  317. #endif
  318. if (ret < 0) {
  319. /* Oops, failed. Gotta free everything */
  320. SDL_free(thread->name);
  321. SDL_free(thread);
  322. thread = NULL;
  323. }
  324. /* Everything is running now */
  325. return thread;
  326. }
  327. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  328. DECLSPEC SDL_Thread *SDLCALL
  329. SDL_CreateThread(int(SDLCALL *fn)(void *),
  330. const char *name, void *data,
  331. pfnSDL_CurrentBeginThread pfnBeginThread,
  332. pfnSDL_CurrentEndThread pfnEndThread)
  333. #else
  334. DECLSPEC SDL_Thread *SDLCALL
  335. SDL_CreateThread(int(SDLCALL *fn)(void *),
  336. const char *name, void *data)
  337. #endif
  338. {
  339. /* !!! FIXME: in 2.1, just make stackhint part of the usual API. */
  340. const char *stackhint = SDL_GetHint(SDL_HINT_THREAD_STACK_SIZE);
  341. size_t stacksize = 0;
  342. /* If the SDL_HINT_THREAD_STACK_SIZE exists, use it */
  343. if (stackhint != NULL) {
  344. char *endp = NULL;
  345. const Sint64 hintval = SDL_strtoll(stackhint, &endp, 10);
  346. if ((*stackhint != '\0') && (*endp == '\0')) { /* a valid number? */
  347. if (hintval > 0) { /* reject bogus values. */
  348. stacksize = (size_t)hintval;
  349. }
  350. }
  351. }
  352. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  353. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, pfnBeginThread, pfnEndThread);
  354. #else
  355. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  356. #endif
  357. }
  358. SDL_Thread *
  359. SDL_CreateThreadInternal(int(SDLCALL *fn)(void *), const char *name,
  360. const size_t stacksize, void *data)
  361. {
  362. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  363. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, NULL, NULL);
  364. #else
  365. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  366. #endif
  367. }
  368. SDL_threadID
  369. SDL_GetThreadID(SDL_Thread *thread)
  370. {
  371. SDL_threadID id;
  372. if (thread) {
  373. id = thread->threadid;
  374. } else {
  375. id = SDL_ThreadID();
  376. }
  377. return id;
  378. }
  379. const char *
  380. SDL_GetThreadName(SDL_Thread *thread)
  381. {
  382. if (thread) {
  383. return thread->name;
  384. } else {
  385. return NULL;
  386. }
  387. }
  388. int SDL_SetThreadPriority(SDL_ThreadPriority priority)
  389. {
  390. return SDL_SYS_SetThreadPriority(priority);
  391. }
  392. void SDL_WaitThread(SDL_Thread *thread, int *status)
  393. {
  394. if (thread) {
  395. SDL_SYS_WaitThread(thread);
  396. if (status) {
  397. *status = thread->status;
  398. }
  399. if (thread->name) {
  400. SDL_free(thread->name);
  401. }
  402. SDL_free(thread);
  403. }
  404. }
  405. void SDL_DetachThread(SDL_Thread *thread)
  406. {
  407. if (thread == NULL) {
  408. return;
  409. }
  410. /* Grab dibs if the state is alive+joinable. */
  411. if (SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_DETACHED)) {
  412. SDL_SYS_DetachThread(thread);
  413. } else {
  414. /* all other states are pretty final, see where we landed. */
  415. const int thread_state = SDL_AtomicGet(&thread->state);
  416. if ((thread_state == SDL_THREAD_STATE_DETACHED) || (thread_state == SDL_THREAD_STATE_CLEANED)) {
  417. return; /* already detached (you shouldn't call this twice!) */
  418. } else if (thread_state == SDL_THREAD_STATE_ZOMBIE) {
  419. SDL_WaitThread(thread, NULL); /* already done, clean it up. */
  420. } else {
  421. SDL_assert(0 && "Unexpected thread state");
  422. }
  423. }
  424. }
  425. int SDL_SemWait(SDL_sem *sem)
  426. {
  427. return SDL_SemWaitTimeoutNS(sem, SDL_MUTEX_MAXWAIT);
  428. }
  429. int SDL_SemTryWait(SDL_sem *sem)
  430. {
  431. return SDL_SemWaitTimeoutNS(sem, 0);
  432. }
  433. int SDL_SemWaitTimeout(SDL_sem *sem, Sint32 timeoutMS)
  434. {
  435. Sint64 timeoutNS;
  436. if (timeoutMS >= 0) {
  437. timeoutNS = SDL_MS_TO_NS(timeoutMS);
  438. } else {
  439. timeoutNS = -1;
  440. }
  441. return SDL_SemWaitTimeoutNS(sem, timeoutNS);
  442. }
  443. int SDL_CondWait(SDL_cond *cond, SDL_mutex *mutex)
  444. {
  445. return SDL_CondWaitTimeoutNS(cond, mutex, SDL_MUTEX_MAXWAIT);
  446. }
  447. int SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Sint32 timeoutMS)
  448. {
  449. Sint64 timeoutNS;
  450. if (timeoutMS >= 0) {
  451. timeoutNS = SDL_MS_TO_NS(timeoutMS);
  452. } else {
  453. timeoutNS = -1;
  454. }
  455. return SDL_CondWaitTimeoutNS(cond, mutex, timeoutNS);
  456. }