SDL_thread.c 15 KB

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