SDL_thread.c 14 KB

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