SDL_thread.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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_c.h"
  21. #include "SDL_systhread.h"
  22. #include "../SDL_error_c.h"
  23. // The storage is local to the thread, but the IDs are global for the process
  24. static SDL_AtomicInt SDL_tls_allocated;
  25. static SDL_AtomicInt SDL_tls_id;
  26. void SDL_InitTLSData(void)
  27. {
  28. SDL_SYS_InitTLSData();
  29. }
  30. void *SDL_GetTLS(SDL_TLSID *id)
  31. {
  32. SDL_TLSData *storage;
  33. int storage_index;
  34. if (id == NULL) {
  35. SDL_InvalidParamError("id");
  36. return NULL;
  37. }
  38. storage_index = SDL_GetAtomicInt(id) - 1;
  39. storage = SDL_SYS_GetTLSData();
  40. if (!storage || storage_index < 0 || storage_index >= storage->limit) {
  41. return NULL;
  42. }
  43. return storage->array[storage_index].data;
  44. }
  45. bool SDL_SetTLS(SDL_TLSID *id, const void *value, SDL_TLSDestructorCallback destructor)
  46. {
  47. SDL_TLSData *storage;
  48. int storage_index;
  49. if (id == NULL) {
  50. return SDL_InvalidParamError("id");
  51. }
  52. /* Make sure TLS is initialized.
  53. * There's a race condition here if you are calling this from non-SDL threads
  54. * and haven't called SDL_Init() on your main thread, but such is life.
  55. */
  56. SDL_InitTLSData();
  57. // Get the storage index associated with the ID in a thread-safe way
  58. storage_index = SDL_GetAtomicInt(id) - 1;
  59. if (storage_index < 0) {
  60. int new_id = (SDL_AtomicIncRef(&SDL_tls_id) + 1);
  61. SDL_CompareAndSwapAtomicInt(id, 0, new_id);
  62. /* If there was a race condition we'll have wasted an ID, but every thread
  63. * will have the same storage index for this id.
  64. */
  65. storage_index = SDL_GetAtomicInt(id) - 1;
  66. }
  67. // Get the storage for the current thread
  68. storage = SDL_SYS_GetTLSData();
  69. if (!storage || storage_index >= storage->limit) {
  70. unsigned int i, oldlimit, newlimit;
  71. SDL_TLSData *new_storage;
  72. oldlimit = storage ? storage->limit : 0;
  73. newlimit = (storage_index + TLS_ALLOC_CHUNKSIZE);
  74. new_storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0]));
  75. if (!new_storage) {
  76. return false;
  77. }
  78. storage = new_storage;
  79. storage->limit = newlimit;
  80. for (i = oldlimit; i < newlimit; ++i) {
  81. storage->array[i].data = NULL;
  82. storage->array[i].destructor = NULL;
  83. }
  84. if (!SDL_SYS_SetTLSData(storage)) {
  85. SDL_free(storage);
  86. return false;
  87. }
  88. SDL_AtomicIncRef(&SDL_tls_allocated);
  89. }
  90. storage->array[storage_index].data = SDL_const_cast(void *, value);
  91. storage->array[storage_index].destructor = destructor;
  92. return true;
  93. }
  94. void SDL_CleanupTLS(void)
  95. {
  96. SDL_TLSData *storage;
  97. // Cleanup the storage for the current thread
  98. storage = SDL_SYS_GetTLSData();
  99. if (storage) {
  100. int i;
  101. for (i = 0; i < storage->limit; ++i) {
  102. if (storage->array[i].destructor) {
  103. storage->array[i].destructor(storage->array[i].data);
  104. }
  105. }
  106. SDL_SYS_SetTLSData(NULL);
  107. SDL_free(storage);
  108. (void)SDL_AtomicDecRef(&SDL_tls_allocated);
  109. }
  110. }
  111. void SDL_QuitTLSData(void)
  112. {
  113. SDL_CleanupTLS();
  114. if (SDL_GetAtomicInt(&SDL_tls_allocated) == 0) {
  115. SDL_SYS_QuitTLSData();
  116. } else {
  117. // Some thread hasn't called SDL_CleanupTLS()
  118. }
  119. }
  120. /* This is a generic implementation of thread-local storage which doesn't
  121. require additional OS support.
  122. It is not especially efficient and doesn't clean up thread-local storage
  123. as threads exit. If there is a real OS that doesn't support thread-local
  124. storage this implementation should be improved to be production quality.
  125. */
  126. typedef struct SDL_TLSEntry
  127. {
  128. SDL_ThreadID thread;
  129. SDL_TLSData *storage;
  130. struct SDL_TLSEntry *next;
  131. } SDL_TLSEntry;
  132. static SDL_Mutex *SDL_generic_TLS_mutex;
  133. static SDL_TLSEntry *SDL_generic_TLS;
  134. void SDL_Generic_InitTLSData(void)
  135. {
  136. if (!SDL_generic_TLS_mutex) {
  137. SDL_generic_TLS_mutex = SDL_CreateMutex();
  138. }
  139. }
  140. SDL_TLSData *SDL_Generic_GetTLSData(void)
  141. {
  142. SDL_ThreadID thread = SDL_GetCurrentThreadID();
  143. SDL_TLSEntry *entry;
  144. SDL_TLSData *storage = NULL;
  145. SDL_LockMutex(SDL_generic_TLS_mutex);
  146. for (entry = SDL_generic_TLS; entry; entry = entry->next) {
  147. if (entry->thread == thread) {
  148. storage = entry->storage;
  149. break;
  150. }
  151. }
  152. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  153. return storage;
  154. }
  155. bool SDL_Generic_SetTLSData(SDL_TLSData *data)
  156. {
  157. SDL_ThreadID thread = SDL_GetCurrentThreadID();
  158. SDL_TLSEntry *prev, *entry;
  159. bool result = true;
  160. SDL_LockMutex(SDL_generic_TLS_mutex);
  161. prev = NULL;
  162. for (entry = SDL_generic_TLS; entry; entry = entry->next) {
  163. if (entry->thread == thread) {
  164. if (data) {
  165. entry->storage = data;
  166. } else {
  167. if (prev) {
  168. prev->next = entry->next;
  169. } else {
  170. SDL_generic_TLS = entry->next;
  171. }
  172. SDL_free(entry);
  173. }
  174. break;
  175. }
  176. prev = entry;
  177. }
  178. if (!entry && data) {
  179. entry = (SDL_TLSEntry *)SDL_malloc(sizeof(*entry));
  180. if (entry) {
  181. entry->thread = thread;
  182. entry->storage = data;
  183. entry->next = SDL_generic_TLS;
  184. SDL_generic_TLS = entry;
  185. } else {
  186. result = false;
  187. }
  188. }
  189. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  190. return result;
  191. }
  192. void SDL_Generic_QuitTLSData(void)
  193. {
  194. SDL_TLSEntry *entry;
  195. // This should have been cleaned up by the time we get here
  196. SDL_assert(!SDL_generic_TLS);
  197. if (SDL_generic_TLS) {
  198. SDL_LockMutex(SDL_generic_TLS_mutex);
  199. for (entry = SDL_generic_TLS; entry; ) {
  200. SDL_TLSEntry *next = entry->next;
  201. SDL_free(entry->storage);
  202. SDL_free(entry);
  203. entry = next;
  204. }
  205. SDL_generic_TLS = NULL;
  206. SDL_UnlockMutex(SDL_generic_TLS_mutex);
  207. }
  208. if (SDL_generic_TLS_mutex) {
  209. SDL_DestroyMutex(SDL_generic_TLS_mutex);
  210. SDL_generic_TLS_mutex = NULL;
  211. }
  212. }
  213. // Non-thread-safe global error variable
  214. static SDL_error *SDL_GetStaticErrBuf(void)
  215. {
  216. static SDL_error SDL_global_error;
  217. static char SDL_global_error_str[128];
  218. SDL_global_error.str = SDL_global_error_str;
  219. SDL_global_error.len = sizeof(SDL_global_error_str);
  220. return &SDL_global_error;
  221. }
  222. #ifndef SDL_THREADS_DISABLED
  223. static void SDLCALL SDL_FreeErrBuf(void *data)
  224. {
  225. SDL_error *errbuf = (SDL_error *)data;
  226. if (errbuf->str) {
  227. errbuf->free_func(errbuf->str);
  228. }
  229. errbuf->free_func(errbuf);
  230. }
  231. #endif
  232. // Routine to get the thread-specific error variable
  233. SDL_error *SDL_GetErrBuf(bool create)
  234. {
  235. #ifdef SDL_THREADS_DISABLED
  236. return SDL_GetStaticErrBuf();
  237. #else
  238. static SDL_TLSID tls_errbuf;
  239. SDL_error *errbuf;
  240. errbuf = (SDL_error *)SDL_GetTLS(&tls_errbuf);
  241. if (!errbuf) {
  242. if (!create) {
  243. return NULL;
  244. }
  245. /* Get the original memory functions for this allocation because the lifetime
  246. * of the error buffer may span calls to SDL_SetMemoryFunctions() by the app
  247. */
  248. SDL_realloc_func realloc_func;
  249. SDL_free_func free_func;
  250. SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);
  251. errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));
  252. if (!errbuf) {
  253. return SDL_GetStaticErrBuf();
  254. }
  255. SDL_zerop(errbuf);
  256. errbuf->realloc_func = realloc_func;
  257. errbuf->free_func = free_func;
  258. SDL_SetTLS(&tls_errbuf, errbuf, SDL_FreeErrBuf);
  259. }
  260. return errbuf;
  261. #endif // SDL_THREADS_DISABLED
  262. }
  263. void SDL_RunThread(SDL_Thread *thread)
  264. {
  265. void *userdata = thread->userdata;
  266. int(SDLCALL * userfunc)(void *) = thread->userfunc;
  267. int *statusloc = &thread->status;
  268. // Perform any system-dependent setup - this function may not fail
  269. SDL_SYS_SetupThread(thread->name);
  270. // Get the thread id
  271. thread->threadid = SDL_GetCurrentThreadID();
  272. // Run the function
  273. *statusloc = userfunc(userdata);
  274. // Clean up thread-local storage
  275. SDL_CleanupTLS();
  276. // Mark us as ready to be joined (or detached)
  277. if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_ZOMBIE)) {
  278. // Clean up if something already detached us.
  279. if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_STATE_DETACHED, SDL_THREAD_STATE_CLEANED)) {
  280. SDL_free(thread->name); // Can't free later, we've already cleaned up TLS
  281. SDL_free(thread);
  282. }
  283. }
  284. }
  285. SDL_Thread *SDL_CreateThreadWithPropertiesRuntime(SDL_PropertiesID props,
  286. SDL_FunctionPointer pfnBeginThread,
  287. SDL_FunctionPointer pfnEndThread)
  288. {
  289. // rather than check this in every backend, just make sure it's correct upfront. Only allow non-NULL if Windows, or Microsoft GDK.
  290. #if !defined(SDL_PLATFORM_WINDOWS)
  291. if (pfnBeginThread || pfnEndThread) {
  292. SDL_SetError("_beginthreadex/_endthreadex not supported on this platform");
  293. return NULL;
  294. }
  295. #endif
  296. SDL_ThreadFunction fn = (SDL_ThreadFunction) SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, NULL);
  297. const char *name = SDL_GetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, NULL);
  298. const size_t stacksize = (size_t) SDL_GetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, 0);
  299. void *userdata = SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, NULL);
  300. if (!fn) {
  301. SDL_SetError("Thread entry function is NULL");
  302. return NULL;
  303. }
  304. SDL_InitMainThread();
  305. SDL_Thread *thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread));
  306. if (!thread) {
  307. return NULL;
  308. }
  309. thread->status = -1;
  310. SDL_SetAtomicInt(&thread->state, SDL_THREAD_STATE_ALIVE);
  311. // Set up the arguments for the thread
  312. if (name) {
  313. thread->name = SDL_strdup(name);
  314. if (!thread->name) {
  315. SDL_free(thread);
  316. return NULL;
  317. }
  318. }
  319. thread->userfunc = fn;
  320. thread->userdata = userdata;
  321. thread->stacksize = stacksize;
  322. // Create the thread and go!
  323. if (!SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread)) {
  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. SDL_Thread *SDL_CreateThreadRuntime(SDL_ThreadFunction fn,
  333. const char *name, void *userdata,
  334. SDL_FunctionPointer pfnBeginThread,
  335. SDL_FunctionPointer pfnEndThread)
  336. {
  337. const SDL_PropertiesID props = SDL_CreateProperties();
  338. SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn);
  339. SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);
  340. SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata);
  341. SDL_Thread *thread = SDL_CreateThreadWithPropertiesRuntime(props, pfnBeginThread, pfnEndThread);
  342. SDL_DestroyProperties(props);
  343. return thread;
  344. }
  345. // internal helper function, not in the public API.
  346. SDL_Thread *SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, size_t stacksize, void *userdata)
  347. {
  348. const SDL_PropertiesID props = SDL_CreateProperties();
  349. SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn);
  350. SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);
  351. SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata);
  352. SDL_SetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, (Sint64) stacksize);
  353. SDL_Thread *thread = SDL_CreateThreadWithProperties(props);
  354. SDL_DestroyProperties(props);
  355. return thread;
  356. }
  357. SDL_ThreadID SDL_GetThreadID(SDL_Thread *thread)
  358. {
  359. SDL_ThreadID id;
  360. if (thread) {
  361. id = thread->threadid;
  362. } else {
  363. id = SDL_GetCurrentThreadID();
  364. }
  365. return id;
  366. }
  367. const char *SDL_GetThreadName(SDL_Thread *thread)
  368. {
  369. if (thread) {
  370. return SDL_GetPersistentString(thread->name);
  371. } else {
  372. return NULL;
  373. }
  374. }
  375. bool SDL_SetCurrentThreadPriority(SDL_ThreadPriority priority)
  376. {
  377. return SDL_SYS_SetThreadPriority(priority);
  378. }
  379. void SDL_WaitThread(SDL_Thread *thread, int *status)
  380. {
  381. if (thread) {
  382. SDL_SYS_WaitThread(thread);
  383. if (status) {
  384. *status = thread->status;
  385. }
  386. SDL_free(thread->name);
  387. SDL_free(thread);
  388. }
  389. }
  390. void SDL_DetachThread(SDL_Thread *thread)
  391. {
  392. if (!thread) {
  393. return;
  394. }
  395. // Grab dibs if the state is alive+joinable.
  396. if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_STATE_ALIVE, SDL_THREAD_STATE_DETACHED)) {
  397. SDL_SYS_DetachThread(thread);
  398. } else {
  399. // all other states are pretty final, see where we landed.
  400. const int thread_state = SDL_GetAtomicInt(&thread->state);
  401. if ((thread_state == SDL_THREAD_STATE_DETACHED) || (thread_state == SDL_THREAD_STATE_CLEANED)) {
  402. return; // already detached (you shouldn't call this twice!)
  403. } else if (thread_state == SDL_THREAD_STATE_ZOMBIE) {
  404. SDL_WaitThread(thread, NULL); // already done, clean it up.
  405. } else {
  406. SDL_assert(0 && "Unexpected thread state");
  407. }
  408. }
  409. }
  410. void SDL_WaitSemaphore(SDL_Semaphore *sem)
  411. {
  412. SDL_WaitSemaphoreTimeoutNS(sem, -1);
  413. }
  414. bool SDL_TryWaitSemaphore(SDL_Semaphore *sem)
  415. {
  416. return SDL_WaitSemaphoreTimeoutNS(sem, 0);
  417. }
  418. bool SDL_WaitSemaphoreTimeout(SDL_Semaphore *sem, Sint32 timeoutMS)
  419. {
  420. Sint64 timeoutNS;
  421. if (timeoutMS >= 0) {
  422. timeoutNS = SDL_MS_TO_NS(timeoutMS);
  423. } else {
  424. timeoutNS = -1;
  425. }
  426. return SDL_WaitSemaphoreTimeoutNS(sem, timeoutNS);
  427. }
  428. void SDL_WaitCondition(SDL_Condition *cond, SDL_Mutex *mutex)
  429. {
  430. SDL_WaitConditionTimeoutNS(cond, mutex, -1);
  431. }
  432. bool SDL_WaitConditionTimeout(SDL_Condition *cond, SDL_Mutex *mutex, Sint32 timeoutMS)
  433. {
  434. Sint64 timeoutNS;
  435. if (timeoutMS >= 0) {
  436. timeoutNS = SDL_MS_TO_NS(timeoutMS);
  437. } else {
  438. timeoutNS = -1;
  439. }
  440. return SDL_WaitConditionTimeoutNS(cond, mutex, timeoutNS);
  441. }
  442. bool SDL_ShouldInit(SDL_InitState *state)
  443. {
  444. while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_INITIALIZED) {
  445. if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED, SDL_INIT_STATUS_INITIALIZING)) {
  446. state->thread = SDL_GetCurrentThreadID();
  447. return true;
  448. }
  449. // Wait for the other thread to complete transition
  450. SDL_Delay(1);
  451. }
  452. return false;
  453. }
  454. bool SDL_ShouldQuit(SDL_InitState *state)
  455. {
  456. while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_UNINITIALIZED) {
  457. if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED, SDL_INIT_STATUS_UNINITIALIZING)) {
  458. state->thread = SDL_GetCurrentThreadID();
  459. return true;
  460. }
  461. // Wait for the other thread to complete transition
  462. SDL_Delay(1);
  463. }
  464. return false;
  465. }
  466. void SDL_SetInitialized(SDL_InitState *state, bool initialized)
  467. {
  468. SDL_assert(state->thread == SDL_GetCurrentThreadID());
  469. if (initialized) {
  470. SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED);
  471. } else {
  472. SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED);
  473. }
  474. }