SDL_thread.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. static void SDLCALL
  184. SDL_FreeErrBuf(void *data)
  185. {
  186. SDL_error *errbuf = (SDL_error *)data;
  187. if (errbuf->str) {
  188. errbuf->free_func(errbuf->str);
  189. }
  190. errbuf->free_func(errbuf);
  191. }
  192. /* Routine to get the thread-specific error variable */
  193. SDL_error *
  194. SDL_GetErrBuf(void)
  195. {
  196. #if SDL_THREADS_DISABLED
  197. return SDL_GetStaticErrBuf();
  198. #else
  199. static SDL_SpinLock tls_lock;
  200. static SDL_bool tls_being_created;
  201. static SDL_TLSID tls_errbuf;
  202. const SDL_error *ALLOCATION_IN_PROGRESS = (SDL_error *)-1;
  203. SDL_error *errbuf;
  204. /* tls_being_created is there simply to prevent recursion if SDL_TLSCreate() fails.
  205. It also means it's possible for another thread to also use SDL_global_errbuf,
  206. but that's very unlikely and hopefully won't cause issues.
  207. */
  208. if (!tls_errbuf && !tls_being_created) {
  209. SDL_AtomicLock(&tls_lock);
  210. if (!tls_errbuf) {
  211. SDL_TLSID slot;
  212. tls_being_created = SDL_TRUE;
  213. slot = SDL_TLSCreate();
  214. tls_being_created = SDL_FALSE;
  215. SDL_MemoryBarrierRelease();
  216. tls_errbuf = slot;
  217. }
  218. SDL_AtomicUnlock(&tls_lock);
  219. }
  220. if (!tls_errbuf) {
  221. return SDL_GetStaticErrBuf();
  222. }
  223. SDL_MemoryBarrierAcquire();
  224. errbuf = (SDL_error *)SDL_TLSGet(tls_errbuf);
  225. if (errbuf == ALLOCATION_IN_PROGRESS) {
  226. return SDL_GetStaticErrBuf();
  227. }
  228. if (!errbuf) {
  229. /* Get the original memory functions for this allocation because the lifetime
  230. * of the error buffer may span calls to SDL_SetMemoryFunctions() by the app
  231. */
  232. SDL_realloc_func realloc_func;
  233. SDL_free_func free_func;
  234. SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);
  235. /* Mark that we're in the middle of allocating our buffer */
  236. SDL_TLSSet(tls_errbuf, ALLOCATION_IN_PROGRESS, NULL);
  237. errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));
  238. if (!errbuf) {
  239. SDL_TLSSet(tls_errbuf, NULL, NULL);
  240. return SDL_GetStaticErrBuf();
  241. }
  242. SDL_zerop(errbuf);
  243. errbuf->realloc_func = realloc_func;
  244. errbuf->free_func = free_func;
  245. SDL_TLSSet(tls_errbuf, errbuf, SDL_FreeErrBuf);
  246. }
  247. return errbuf;
  248. #endif /* SDL_THREADS_DISABLED */
  249. }
  250. void
  251. SDL_RunThread(SDL_Thread *thread)
  252. {
  253. void *userdata = thread->userdata;
  254. int (SDLCALL * userfunc) (void *) = thread->userfunc;
  255. int *statusloc = &thread->status;
  256. /* Perform any system-dependent setup - this function may not fail */
  257. SDL_SYS_SetupThread(thread->name);
  258. /* Get the thread id */
  259. thread->threadid = SDL_ThreadID();
  260. /* Run the function */
  261. *statusloc = userfunc(userdata);
  262. /* Clean up thread-local storage */
  263. SDL_TLSCleanup();
  264. /* Mark us as ready to be joined (or detached) */
  265. if (!SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_ZOMBIE)) {
  266. /* Clean up if something already detached us. */
  267. if (SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_DETACHED, SDL_THREAD_STATE_CLEANED)) {
  268. if (thread->name) {
  269. SDL_free(thread->name);
  270. }
  271. SDL_free(thread);
  272. }
  273. }
  274. }
  275. #ifdef SDL_CreateThread
  276. #undef SDL_CreateThread
  277. #undef SDL_CreateThreadWithStackSize
  278. #endif
  279. #if SDL_DYNAMIC_API
  280. #define SDL_CreateThread SDL_CreateThread_REAL
  281. #define SDL_CreateThreadWithStackSize SDL_CreateThreadWithStackSize_REAL
  282. #endif
  283. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  284. SDL_Thread *
  285. SDL_CreateThreadWithStackSize(int (SDLCALL * fn) (void *),
  286. const char *name, const size_t stacksize, void *data,
  287. pfnSDL_CurrentBeginThread pfnBeginThread,
  288. pfnSDL_CurrentEndThread pfnEndThread)
  289. #else
  290. SDL_Thread *
  291. SDL_CreateThreadWithStackSize(int (SDLCALL * fn) (void *),
  292. const char *name, const size_t stacksize, void *data)
  293. #endif
  294. {
  295. SDL_Thread *thread;
  296. int ret;
  297. /* Allocate memory for the thread info structure */
  298. thread = (SDL_Thread *) SDL_calloc(1, sizeof(*thread));
  299. if (thread == NULL) {
  300. SDL_OutOfMemory();
  301. return NULL;
  302. }
  303. thread->status = -1;
  304. SDL_AtomicSet(&thread->state, SDL_THREAD_STATE_ALIVE);
  305. /* Set up the arguments for the thread */
  306. if (name != NULL) {
  307. thread->name = SDL_strdup(name);
  308. if (thread->name == NULL) {
  309. SDL_OutOfMemory();
  310. SDL_free(thread);
  311. return NULL;
  312. }
  313. }
  314. thread->userfunc = fn;
  315. thread->userdata = data;
  316. thread->stacksize = stacksize;
  317. /* Create the thread and go! */
  318. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  319. ret = SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread);
  320. #else
  321. ret = SDL_SYS_CreateThread(thread);
  322. #endif
  323. if (ret < 0) {
  324. /* Oops, failed. Gotta free everything */
  325. SDL_free(thread->name);
  326. SDL_free(thread);
  327. thread = NULL;
  328. }
  329. /* Everything is running now */
  330. return thread;
  331. }
  332. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  333. DECLSPEC SDL_Thread *SDLCALL
  334. SDL_CreateThread(int (SDLCALL * fn) (void *),
  335. const char *name, void *data,
  336. pfnSDL_CurrentBeginThread pfnBeginThread,
  337. pfnSDL_CurrentEndThread pfnEndThread)
  338. #else
  339. DECLSPEC SDL_Thread *SDLCALL
  340. SDL_CreateThread(int (SDLCALL * fn) (void *),
  341. const char *name, void *data)
  342. #endif
  343. {
  344. /* !!! FIXME: in 2.1, just make stackhint part of the usual API. */
  345. const char *stackhint = SDL_GetHint(SDL_HINT_THREAD_STACK_SIZE);
  346. size_t stacksize = 0;
  347. /* If the SDL_HINT_THREAD_STACK_SIZE exists, use it */
  348. if (stackhint != NULL) {
  349. char *endp = NULL;
  350. const Sint64 hintval = SDL_strtoll(stackhint, &endp, 10);
  351. if ((*stackhint != '\0') && (*endp == '\0')) { /* a valid number? */
  352. if (hintval > 0) { /* reject bogus values. */
  353. stacksize = (size_t) hintval;
  354. }
  355. }
  356. }
  357. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  358. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, pfnBeginThread, pfnEndThread);
  359. #else
  360. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  361. #endif
  362. }
  363. SDL_Thread *
  364. SDL_CreateThreadInternal(int (SDLCALL * fn) (void *), const char *name,
  365. const size_t stacksize, void *data) {
  366. #ifdef SDL_PASSED_BEGINTHREAD_ENDTHREAD
  367. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data, NULL, NULL);
  368. #else
  369. return SDL_CreateThreadWithStackSize(fn, name, stacksize, data);
  370. #endif
  371. }
  372. SDL_threadID
  373. SDL_GetThreadID(SDL_Thread * thread)
  374. {
  375. SDL_threadID id;
  376. if (thread) {
  377. id = thread->threadid;
  378. } else {
  379. id = SDL_ThreadID();
  380. }
  381. return id;
  382. }
  383. const char *
  384. SDL_GetThreadName(SDL_Thread * thread)
  385. {
  386. if (thread) {
  387. return thread->name;
  388. } else {
  389. return NULL;
  390. }
  391. }
  392. int
  393. SDL_SetThreadPriority(SDL_ThreadPriority priority)
  394. {
  395. return SDL_SYS_SetThreadPriority(priority);
  396. }
  397. void
  398. SDL_WaitThread(SDL_Thread * thread, int *status)
  399. {
  400. if (thread) {
  401. SDL_SYS_WaitThread(thread);
  402. if (status) {
  403. *status = thread->status;
  404. }
  405. if (thread->name) {
  406. SDL_free(thread->name);
  407. }
  408. SDL_free(thread);
  409. }
  410. }
  411. void
  412. SDL_DetachThread(SDL_Thread * thread)
  413. {
  414. if (!thread) {
  415. return;
  416. }
  417. /* Grab dibs if the state is alive+joinable. */
  418. if (SDL_AtomicCAS(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_DETACHED)) {
  419. SDL_SYS_DetachThread(thread);
  420. } else {
  421. /* all other states are pretty final, see where we landed. */
  422. const int thread_state = SDL_AtomicGet(&thread->state);
  423. if ((thread_state == SDL_THREAD_STATE_DETACHED) || (thread_state == SDL_THREAD_STATE_CLEANED)) {
  424. return; /* already detached (you shouldn't call this twice!) */
  425. } else if (thread_state == SDL_THREAD_STATE_ZOMBIE) {
  426. SDL_WaitThread(thread, NULL); /* already done, clean it up. */
  427. } else {
  428. SDL_assert(0 && "Unexpected thread state");
  429. }
  430. }
  431. }
  432. /* vi: set ts=4 sw=4 expandtab: */