1
0

SDL_thread.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. SDL_TLSID SDL_TLSCreate(void)
  26. {
  27. static SDL_atomic_t SDL_tls_id;
  28. return SDL_AtomicIncRef(&SDL_tls_id) + 1;
  29. }
  30. void *SDL_TLSGet(SDL_TLSID id)
  31. {
  32. SDL_TLSData *storage;
  33. storage = SDL_SYS_GetTLSData();
  34. if (!storage || 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 || (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) {
  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(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_ThreadID();
  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_AtomicLock(&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_AtomicUnlock(&tls_lock);
  111. return NULL;
  112. }
  113. }
  114. SDL_AtomicUnlock(&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_ThreadID();
  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. if (!entry) {
  164. return SDL_OutOfMemory();
  165. }
  166. return 0;
  167. }
  168. /* Non-thread-safe global error variable */
  169. static SDL_error *SDL_GetStaticErrBuf(void)
  170. {
  171. static SDL_error SDL_global_error;
  172. static char SDL_global_error_str[128];
  173. SDL_global_error.str = SDL_global_error_str;
  174. SDL_global_error.len = sizeof(SDL_global_error_str);
  175. return &SDL_global_error;
  176. }
  177. #ifndef SDL_THREADS_DISABLED
  178. static void SDLCALL SDL_FreeErrBuf(void *data)
  179. {
  180. SDL_error *errbuf = (SDL_error *)data;
  181. if (errbuf->str) {
  182. errbuf->free_func(errbuf->str);
  183. }
  184. errbuf->free_func(errbuf);
  185. }
  186. #endif
  187. /* Routine to get the thread-specific error variable */
  188. SDL_error *SDL_GetErrBuf(void)
  189. {
  190. #ifdef SDL_THREADS_DISABLED
  191. return SDL_GetStaticErrBuf();
  192. #else
  193. static SDL_SpinLock tls_lock;
  194. static SDL_bool tls_being_created;
  195. static SDL_TLSID tls_errbuf;
  196. const SDL_error *ALLOCATION_IN_PROGRESS = (SDL_error *)-1;
  197. SDL_error *errbuf;
  198. /* tls_being_created is there simply to prevent recursion if SDL_TLSCreate() 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_AtomicLock(&tls_lock);
  204. if (!tls_errbuf) {
  205. SDL_TLSID slot;
  206. tls_being_created = SDL_TRUE;
  207. slot = SDL_TLSCreate();
  208. tls_being_created = SDL_FALSE;
  209. SDL_MemoryBarrierRelease();
  210. tls_errbuf = slot;
  211. }
  212. SDL_AtomicUnlock(&tls_lock);
  213. }
  214. if (!tls_errbuf) {
  215. return SDL_GetStaticErrBuf();
  216. }
  217. SDL_MemoryBarrierAcquire();
  218. errbuf = (SDL_error *)SDL_TLSGet(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_TLSSet(tls_errbuf, ALLOCATION_IN_PROGRESS, NULL);
  231. errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));
  232. if (!errbuf) {
  233. SDL_TLSSet(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_TLSSet(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_ThreadID();
  253. /* Run the function */
  254. *statusloc = userfunc(userdata);
  255. /* Clean up thread-local storage */
  256. SDL_TLSCleanup();
  257. /* Mark us as ready to be joined (or detached) */
  258. if (!SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_ZOMBIE)) {
  259. /* Clean up if something already detached us. */
  260. if (SDL_AtomicCAS(&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. SDL_OutOfMemory();
  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_OutOfMemory();
  301. SDL_free(thread);
  302. return NULL;
  303. }
  304. }
  305. thread->userfunc = fn;
  306. thread->userdata = data;
  307. thread->stacksize = stacksize;
  308. /* Create the thread and go! */
  309. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  310. ret = SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread);
  311. #else
  312. ret = SDL_SYS_CreateThread(thread);
  313. #endif
  314. if (ret < 0) {
  315. /* Oops, failed. Gotta free everything */
  316. SDL_free(thread->name);
  317. SDL_free(thread);
  318. thread = NULL;
  319. }
  320. /* Everything is running now */
  321. return thread;
  322. }
  323. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  324. DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(int(SDLCALL *fn)(void *),
  325. const char *name, void *data,
  326. pfnSDL_CurrentBeginThread pfnBeginThread,
  327. pfnSDL_CurrentEndThread pfnEndThread)
  328. #else
  329. DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(int(SDLCALL *fn)(void *),
  330. const char *name, void *data)
  331. #endif
  332. {
  333. /* !!! FIXME: in 2.1, just make stackhint part of the usual API. */
  334. const char *stackhint = SDL_GetHint(SDL_HINT_THREAD_STACK_SIZE);
  335. size_t stacksize = 0;
  336. /* If the SDL_HINT_THREAD_STACK_SIZE exists, use it */
  337. if (stackhint) {
  338. char *endp = NULL;
  339. const Sint64 hintval = SDL_strtoll(stackhint, &endp, 10);
  340. if ((*stackhint != '\0') && (*endp == '\0')) { /* a valid number? */
  341. if (hintval > 0) { /* reject bogus values. */
  342. stacksize = (size_t)hintval;
  343. }
  344. }
  345. }
  346. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  347. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, pfnBeginThread, pfnEndThread);
  348. #else
  349. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  350. #endif
  351. }
  352. SDL_Thread *SDL_CreateThreadInternal(int(SDLCALL *fn)(void *), const char *name,
  353. const size_t stacksize, void *data)
  354. {
  355. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  356. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, NULL, NULL);
  357. #else
  358. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  359. #endif
  360. }
  361. SDL_threadID SDL_GetThreadID(SDL_Thread *thread)
  362. {
  363. SDL_threadID id;
  364. if (thread) {
  365. id = thread->threadid;
  366. } else {
  367. id = SDL_ThreadID();
  368. }
  369. return id;
  370. }
  371. const char *SDL_GetThreadName(SDL_Thread *thread)
  372. {
  373. if (thread) {
  374. return thread->name;
  375. } else {
  376. return NULL;
  377. }
  378. }
  379. int SDL_SetThreadPriority(SDL_ThreadPriority priority)
  380. {
  381. return SDL_SYS_SetThreadPriority(priority);
  382. }
  383. void SDL_WaitThread(SDL_Thread *thread, int *status)
  384. {
  385. if (thread) {
  386. SDL_SYS_WaitThread(thread);
  387. if (status) {
  388. *status = thread->status;
  389. }
  390. if (thread->name) {
  391. SDL_free(thread->name);
  392. }
  393. SDL_free(thread);
  394. }
  395. }
  396. void SDL_DetachThread(SDL_Thread *thread)
  397. {
  398. if (!thread) {
  399. return;
  400. }
  401. /* Grab dibs if the state is alive+joinable. */
  402. if (SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_DETACHED)) {
  403. SDL_SYS_DetachThread(thread);
  404. } else {
  405. /* all other states are pretty final, see where we landed. */
  406. const int thread_state = SDL_AtomicGet(&thread->state);
  407. if ((thread_state == SDL_THREAD_STATE_DETACHED) || (thread_state == SDL_THREAD_STATE_CLEANED)) {
  408. return; /* already detached (you shouldn't call this twice!) */
  409. } else if (thread_state == SDL_THREAD_STATE_ZOMBIE) {
  410. SDL_WaitThread(thread, NULL); /* already done, clean it up. */
  411. } else {
  412. SDL_assert(0 && "Unexpected thread state");
  413. }
  414. }
  415. }
  416. /* vi: set ts=4 sw=4 expandtab: */