SDL_thread.c 13 KB

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