Path: blob/master/thirdparty/sdl/thread/SDL_thread.c
21085 views
/*1Simple DirectMedia Layer2Copyright (C) 1997-2025 Sam Lantinga <[email protected]>34This software is provided 'as-is', without any express or implied5warranty. In no event will the authors be held liable for any damages6arising from the use of this software.78Permission is granted to anyone to use this software for any purpose,9including commercial applications, and to alter it and redistribute it10freely, subject to the following restrictions:11121. The origin of this software must not be misrepresented; you must not13claim that you wrote the original software. If you use this software14in a product, an acknowledgment in the product documentation would be15appreciated but is not required.162. Altered source versions must be plainly marked as such, and must not be17misrepresented as being the original software.183. This notice may not be removed or altered from any source distribution.19*/20#include "SDL_internal.h"2122// System independent thread management routines for SDL2324#include "SDL_thread_c.h"25#include "SDL_systhread.h"26#include "../SDL_error_c.h"2728// The storage is local to the thread, but the IDs are global for the process2930static SDL_AtomicInt SDL_tls_allocated;31static SDL_AtomicInt SDL_tls_id;3233void SDL_InitTLSData(void)34{35SDL_SYS_InitTLSData();36}3738void *SDL_GetTLS(SDL_TLSID *id)39{40SDL_TLSData *storage;41int storage_index;4243if (id == NULL) {44SDL_InvalidParamError("id");45return NULL;46}4748storage_index = SDL_GetAtomicInt(id) - 1;49storage = SDL_SYS_GetTLSData();50if (!storage || storage_index < 0 || storage_index >= storage->limit) {51return NULL;52}53return storage->array[storage_index].data;54}5556bool SDL_SetTLS(SDL_TLSID *id, const void *value, SDL_TLSDestructorCallback destructor)57{58SDL_TLSData *storage;59int storage_index;6061if (id == NULL) {62return SDL_InvalidParamError("id");63}6465/* Make sure TLS is initialized.66* There's a race condition here if you are calling this from non-SDL threads67* and haven't called SDL_Init() on your main thread, but such is life.68*/69SDL_InitTLSData();7071// Get the storage index associated with the ID in a thread-safe way72storage_index = SDL_GetAtomicInt(id) - 1;73if (storage_index < 0) {74int new_id = (SDL_AtomicIncRef(&SDL_tls_id) + 1);7576SDL_CompareAndSwapAtomicInt(id, 0, new_id);7778/* If there was a race condition we'll have wasted an ID, but every thread79* will have the same storage index for this id.80*/81storage_index = SDL_GetAtomicInt(id) - 1;82} else {83// Make sure we don't allocate an ID clobbering this one84int tls_id = SDL_GetAtomicInt(&SDL_tls_id);85while (storage_index >= tls_id) {86if (SDL_CompareAndSwapAtomicInt(&SDL_tls_id, tls_id, storage_index + 1)) {87break;88}89tls_id = SDL_GetAtomicInt(&SDL_tls_id);90}91}9293// Get the storage for the current thread94storage = SDL_SYS_GetTLSData();95if (!storage || storage_index >= storage->limit) {96unsigned int i, oldlimit, newlimit;97SDL_TLSData *new_storage;9899oldlimit = storage ? storage->limit : 0;100newlimit = (storage_index + TLS_ALLOC_CHUNKSIZE);101new_storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0]));102if (!new_storage) {103return false;104}105storage = new_storage;106storage->limit = newlimit;107for (i = oldlimit; i < newlimit; ++i) {108storage->array[i].data = NULL;109storage->array[i].destructor = NULL;110}111if (!SDL_SYS_SetTLSData(storage)) {112SDL_free(storage);113return false;114}115SDL_AtomicIncRef(&SDL_tls_allocated);116}117118storage->array[storage_index].data = SDL_const_cast(void *, value);119storage->array[storage_index].destructor = destructor;120return true;121}122123void SDL_CleanupTLS(void)124{125SDL_TLSData *storage;126127// Cleanup the storage for the current thread128storage = SDL_SYS_GetTLSData();129if (storage) {130int i;131for (i = 0; i < storage->limit; ++i) {132if (storage->array[i].destructor) {133storage->array[i].destructor(storage->array[i].data);134}135}136SDL_SYS_SetTLSData(NULL);137SDL_free(storage);138(void)SDL_AtomicDecRef(&SDL_tls_allocated);139}140}141142void SDL_QuitTLSData(void)143{144SDL_CleanupTLS();145146if (SDL_GetAtomicInt(&SDL_tls_allocated) == 0) {147SDL_SYS_QuitTLSData();148} else {149// Some thread hasn't called SDL_CleanupTLS()150}151}152153/* This is a generic implementation of thread-local storage which doesn't154require additional OS support.155156It is not especially efficient and doesn't clean up thread-local storage157as threads exit. If there is a real OS that doesn't support thread-local158storage this implementation should be improved to be production quality.159*/160161typedef struct SDL_TLSEntry162{163SDL_ThreadID thread;164SDL_TLSData *storage;165struct SDL_TLSEntry *next;166} SDL_TLSEntry;167168static SDL_Mutex *SDL_generic_TLS_mutex;169static SDL_TLSEntry *SDL_generic_TLS;170171void SDL_Generic_InitTLSData(void)172{173if (!SDL_generic_TLS_mutex) {174SDL_generic_TLS_mutex = SDL_CreateMutex();175}176}177178SDL_TLSData *SDL_Generic_GetTLSData(void)179{180SDL_ThreadID thread = SDL_GetCurrentThreadID();181SDL_TLSEntry *entry;182SDL_TLSData *storage = NULL;183184SDL_LockMutex(SDL_generic_TLS_mutex);185for (entry = SDL_generic_TLS; entry; entry = entry->next) {186if (entry->thread == thread) {187storage = entry->storage;188break;189}190}191SDL_UnlockMutex(SDL_generic_TLS_mutex);192193return storage;194}195196bool SDL_Generic_SetTLSData(SDL_TLSData *data)197{198SDL_ThreadID thread = SDL_GetCurrentThreadID();199SDL_TLSEntry *prev, *entry;200bool result = true;201202SDL_LockMutex(SDL_generic_TLS_mutex);203prev = NULL;204for (entry = SDL_generic_TLS; entry; entry = entry->next) {205if (entry->thread == thread) {206if (data) {207entry->storage = data;208} else {209if (prev) {210prev->next = entry->next;211} else {212SDL_generic_TLS = entry->next;213}214SDL_free(entry);215}216break;217}218prev = entry;219}220if (!entry && data) {221entry = (SDL_TLSEntry *)SDL_malloc(sizeof(*entry));222if (entry) {223entry->thread = thread;224entry->storage = data;225entry->next = SDL_generic_TLS;226SDL_generic_TLS = entry;227} else {228result = false;229}230}231SDL_UnlockMutex(SDL_generic_TLS_mutex);232233return result;234}235236void SDL_Generic_QuitTLSData(void)237{238SDL_TLSEntry *entry;239240// This should have been cleaned up by the time we get here241SDL_assert(!SDL_generic_TLS);242if (SDL_generic_TLS) {243SDL_LockMutex(SDL_generic_TLS_mutex);244for (entry = SDL_generic_TLS; entry; ) {245SDL_TLSEntry *next = entry->next;246SDL_free(entry->storage);247SDL_free(entry);248entry = next;249}250SDL_generic_TLS = NULL;251SDL_UnlockMutex(SDL_generic_TLS_mutex);252}253254if (SDL_generic_TLS_mutex) {255SDL_DestroyMutex(SDL_generic_TLS_mutex);256SDL_generic_TLS_mutex = NULL;257}258}259260// Non-thread-safe global error variable261static SDL_error *SDL_GetStaticErrBuf(void)262{263static SDL_error SDL_global_error;264static char SDL_global_error_str[128];265SDL_global_error.str = SDL_global_error_str;266SDL_global_error.len = sizeof(SDL_global_error_str);267return &SDL_global_error;268}269270#ifndef SDL_THREADS_DISABLED271static void SDLCALL SDL_FreeErrBuf(void *data)272{273SDL_error *errbuf = (SDL_error *)data;274275if (errbuf->str) {276errbuf->free_func(errbuf->str);277}278errbuf->free_func(errbuf);279}280#endif281282// Routine to get the thread-specific error variable283SDL_error *SDL_GetErrBuf(bool create)284{285#ifdef SDL_THREADS_DISABLED286return SDL_GetStaticErrBuf();287#else288static SDL_TLSID tls_errbuf;289SDL_error *errbuf;290291errbuf = (SDL_error *)SDL_GetTLS(&tls_errbuf);292if (!errbuf) {293if (!create) {294return NULL;295}296297/* Get the original memory functions for this allocation because the lifetime298* of the error buffer may span calls to SDL_SetMemoryFunctions() by the app299*/300SDL_realloc_func realloc_func;301SDL_free_func free_func;302SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);303304errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));305if (!errbuf) {306return SDL_GetStaticErrBuf();307}308SDL_zerop(errbuf);309errbuf->realloc_func = realloc_func;310errbuf->free_func = free_func;311SDL_SetTLS(&tls_errbuf, errbuf, SDL_FreeErrBuf);312}313return errbuf;314#endif // SDL_THREADS_DISABLED315}316317static bool ThreadValid(SDL_Thread *thread)318{319return SDL_ObjectValid(thread, SDL_OBJECT_TYPE_THREAD);320}321322void SDL_RunThread(SDL_Thread *thread)323{324void *userdata = thread->userdata;325int(SDLCALL *userfunc)(void *) = thread->userfunc;326327int *statusloc = &thread->status;328329// Perform any system-dependent setup - this function may not fail330SDL_SYS_SetupThread(thread->name);331332// Get the thread id333thread->threadid = SDL_GetCurrentThreadID();334335// Run the function336*statusloc = userfunc(userdata);337338// Clean up thread-local storage339SDL_CleanupTLS();340341// Mark us as ready to be joined (or detached)342if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) {343// Clean up if something already detached us.344if (SDL_GetAtomicInt(&thread->state) == SDL_THREAD_DETACHED) {345SDL_free(thread->name); // Can't free later, we've already cleaned up TLS346SDL_free(thread);347}348}349}350351SDL_Thread *SDL_CreateThreadWithPropertiesRuntime(SDL_PropertiesID props,352SDL_FunctionPointer pfnBeginThread,353SDL_FunctionPointer pfnEndThread)354{355// rather than check this in every backend, just make sure it's correct upfront. Only allow non-NULL if Windows, or Microsoft GDK.356#if !defined(SDL_PLATFORM_WINDOWS)357if (pfnBeginThread || pfnEndThread) {358SDL_SetError("_beginthreadex/_endthreadex not supported on this platform");359return NULL;360}361#endif362363SDL_ThreadFunction fn = (SDL_ThreadFunction) SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, NULL);364const char *name = SDL_GetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, NULL);365const size_t stacksize = (size_t) SDL_GetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, 0);366void *userdata = SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, NULL);367368if (!fn) {369SDL_SetError("Thread entry function is NULL");370return NULL;371}372373SDL_InitMainThread();374375SDL_Thread *thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread));376if (!thread) {377return NULL;378}379thread->status = -1;380SDL_SetAtomicInt(&thread->state, SDL_THREAD_ALIVE);381382// Set up the arguments for the thread383if (name) {384thread->name = SDL_strdup(name);385if (!thread->name) {386SDL_free(thread);387return NULL;388}389}390391thread->userfunc = fn;392thread->userdata = userdata;393thread->stacksize = stacksize;394395SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, true);396397// Create the thread and go!398if (!SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread)) {399// Oops, failed. Gotta free everything400SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);401SDL_free(thread->name);402SDL_free(thread);403thread = NULL;404}405406// Everything is running now407return thread;408}409410SDL_Thread *SDL_CreateThreadRuntime(SDL_ThreadFunction fn,411const char *name, void *userdata,412SDL_FunctionPointer pfnBeginThread,413SDL_FunctionPointer pfnEndThread)414{415const SDL_PropertiesID props = SDL_CreateProperties();416SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn);417SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);418SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata);419SDL_Thread *thread = SDL_CreateThreadWithPropertiesRuntime(props, pfnBeginThread, pfnEndThread);420SDL_DestroyProperties(props);421return thread;422}423424// internal helper function, not in the public API.425SDL_Thread *SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, size_t stacksize, void *userdata)426{427const SDL_PropertiesID props = SDL_CreateProperties();428SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn);429SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);430SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata);431SDL_SetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, (Sint64) stacksize);432SDL_Thread *thread = SDL_CreateThreadWithProperties(props);433SDL_DestroyProperties(props);434return thread;435}436437SDL_ThreadID SDL_GetThreadID(SDL_Thread *thread)438{439SDL_ThreadID id = 0;440441if (thread) {442if (ThreadValid(thread)) {443id = thread->threadid;444}445} else {446id = SDL_GetCurrentThreadID();447}448return id;449}450451const char *SDL_GetThreadName(SDL_Thread *thread)452{453if (ThreadValid(thread)) {454return SDL_GetPersistentString(thread->name);455} else {456return NULL;457}458}459460bool SDL_SetCurrentThreadPriority(SDL_ThreadPriority priority)461{462return SDL_SYS_SetThreadPriority(priority);463}464465void SDL_WaitThread(SDL_Thread *thread, int *status)466{467if (!ThreadValid(thread)) {468if (status) {469*status = -1;470}471return;472}473474SDL_SYS_WaitThread(thread);475if (status) {476*status = thread->status;477}478SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);479SDL_free(thread->name);480SDL_free(thread);481}482483SDL_ThreadState SDL_GetThreadState(SDL_Thread *thread)484{485if (!ThreadValid(thread)) {486return SDL_THREAD_UNKNOWN;487}488489return (SDL_ThreadState)SDL_GetAtomicInt(&thread->state);490}491492void SDL_DetachThread(SDL_Thread *thread)493{494if (!ThreadValid(thread)) {495return;496}497498// Grab dibs if the state is alive+joinable.499if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_DETACHED)) {500// The thread may vanish at any time, it's no longer valid501SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);502SDL_SYS_DetachThread(thread);503} else {504// all other states are pretty final, see where we landed.505SDL_ThreadState thread_state = SDL_GetThreadState(thread);506if (thread_state == SDL_THREAD_DETACHED) {507return; // already detached (you shouldn't call this twice!)508} else if (thread_state == SDL_THREAD_COMPLETE) {509SDL_WaitThread(thread, NULL); // already done, clean it up.510}511}512}513514void SDL_WaitSemaphore(SDL_Semaphore *sem)515{516SDL_WaitSemaphoreTimeoutNS(sem, -1);517}518519bool SDL_TryWaitSemaphore(SDL_Semaphore *sem)520{521return SDL_WaitSemaphoreTimeoutNS(sem, 0);522}523524bool SDL_WaitSemaphoreTimeout(SDL_Semaphore *sem, Sint32 timeoutMS)525{526Sint64 timeoutNS;527528if (timeoutMS >= 0) {529timeoutNS = SDL_MS_TO_NS(timeoutMS);530} else {531timeoutNS = -1;532}533return SDL_WaitSemaphoreTimeoutNS(sem, timeoutNS);534}535536void SDL_WaitCondition(SDL_Condition *cond, SDL_Mutex *mutex)537{538SDL_WaitConditionTimeoutNS(cond, mutex, -1);539}540541bool SDL_WaitConditionTimeout(SDL_Condition *cond, SDL_Mutex *mutex, Sint32 timeoutMS)542{543Sint64 timeoutNS;544545if (timeoutMS >= 0) {546timeoutNS = SDL_MS_TO_NS(timeoutMS);547} else {548timeoutNS = -1;549}550return SDL_WaitConditionTimeoutNS(cond, mutex, timeoutNS);551}552553bool SDL_ShouldInit(SDL_InitState *state)554{555while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_INITIALIZED) {556if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED, SDL_INIT_STATUS_INITIALIZING)) {557state->thread = SDL_GetCurrentThreadID();558return true;559}560561// Wait for the other thread to complete transition562SDL_Delay(1);563}564return false;565}566567bool SDL_ShouldQuit(SDL_InitState *state)568{569while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_UNINITIALIZED) {570if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED, SDL_INIT_STATUS_UNINITIALIZING)) {571state->thread = SDL_GetCurrentThreadID();572return true;573}574575// Wait for the other thread to complete transition576SDL_Delay(1);577}578return false;579}580581void SDL_SetInitialized(SDL_InitState *state, bool initialized)582{583SDL_assert(state->thread == SDL_GetCurrentThreadID());584585if (initialized) {586SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED);587} else {588SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED);589}590}591592593594