SDL_thread.c 14 KB

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