Path: blob/master/thirdparty/sdl/thread/SDL_thread.c
10279 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}8384// Get the storage for the current thread85storage = SDL_SYS_GetTLSData();86if (!storage || storage_index >= storage->limit) {87unsigned int i, oldlimit, newlimit;88SDL_TLSData *new_storage;8990oldlimit = storage ? storage->limit : 0;91newlimit = (storage_index + TLS_ALLOC_CHUNKSIZE);92new_storage = (SDL_TLSData *)SDL_realloc(storage, sizeof(*storage) + (newlimit - 1) * sizeof(storage->array[0]));93if (!new_storage) {94return false;95}96storage = new_storage;97storage->limit = newlimit;98for (i = oldlimit; i < newlimit; ++i) {99storage->array[i].data = NULL;100storage->array[i].destructor = NULL;101}102if (!SDL_SYS_SetTLSData(storage)) {103SDL_free(storage);104return false;105}106SDL_AtomicIncRef(&SDL_tls_allocated);107}108109storage->array[storage_index].data = SDL_const_cast(void *, value);110storage->array[storage_index].destructor = destructor;111return true;112}113114void SDL_CleanupTLS(void)115{116SDL_TLSData *storage;117118// Cleanup the storage for the current thread119storage = SDL_SYS_GetTLSData();120if (storage) {121int i;122for (i = 0; i < storage->limit; ++i) {123if (storage->array[i].destructor) {124storage->array[i].destructor(storage->array[i].data);125}126}127SDL_SYS_SetTLSData(NULL);128SDL_free(storage);129(void)SDL_AtomicDecRef(&SDL_tls_allocated);130}131}132133void SDL_QuitTLSData(void)134{135SDL_CleanupTLS();136137if (SDL_GetAtomicInt(&SDL_tls_allocated) == 0) {138SDL_SYS_QuitTLSData();139} else {140// Some thread hasn't called SDL_CleanupTLS()141}142}143144/* This is a generic implementation of thread-local storage which doesn't145require additional OS support.146147It is not especially efficient and doesn't clean up thread-local storage148as threads exit. If there is a real OS that doesn't support thread-local149storage this implementation should be improved to be production quality.150*/151152typedef struct SDL_TLSEntry153{154SDL_ThreadID thread;155SDL_TLSData *storage;156struct SDL_TLSEntry *next;157} SDL_TLSEntry;158159static SDL_Mutex *SDL_generic_TLS_mutex;160static SDL_TLSEntry *SDL_generic_TLS;161162void SDL_Generic_InitTLSData(void)163{164if (!SDL_generic_TLS_mutex) {165SDL_generic_TLS_mutex = SDL_CreateMutex();166}167}168169SDL_TLSData *SDL_Generic_GetTLSData(void)170{171SDL_ThreadID thread = SDL_GetCurrentThreadID();172SDL_TLSEntry *entry;173SDL_TLSData *storage = NULL;174175SDL_LockMutex(SDL_generic_TLS_mutex);176for (entry = SDL_generic_TLS; entry; entry = entry->next) {177if (entry->thread == thread) {178storage = entry->storage;179break;180}181}182SDL_UnlockMutex(SDL_generic_TLS_mutex);183184return storage;185}186187bool SDL_Generic_SetTLSData(SDL_TLSData *data)188{189SDL_ThreadID thread = SDL_GetCurrentThreadID();190SDL_TLSEntry *prev, *entry;191bool result = true;192193SDL_LockMutex(SDL_generic_TLS_mutex);194prev = NULL;195for (entry = SDL_generic_TLS; entry; entry = entry->next) {196if (entry->thread == thread) {197if (data) {198entry->storage = data;199} else {200if (prev) {201prev->next = entry->next;202} else {203SDL_generic_TLS = entry->next;204}205SDL_free(entry);206}207break;208}209prev = entry;210}211if (!entry && data) {212entry = (SDL_TLSEntry *)SDL_malloc(sizeof(*entry));213if (entry) {214entry->thread = thread;215entry->storage = data;216entry->next = SDL_generic_TLS;217SDL_generic_TLS = entry;218} else {219result = false;220}221}222SDL_UnlockMutex(SDL_generic_TLS_mutex);223224return result;225}226227void SDL_Generic_QuitTLSData(void)228{229SDL_TLSEntry *entry;230231// This should have been cleaned up by the time we get here232SDL_assert(!SDL_generic_TLS);233if (SDL_generic_TLS) {234SDL_LockMutex(SDL_generic_TLS_mutex);235for (entry = SDL_generic_TLS; entry; ) {236SDL_TLSEntry *next = entry->next;237SDL_free(entry->storage);238SDL_free(entry);239entry = next;240}241SDL_generic_TLS = NULL;242SDL_UnlockMutex(SDL_generic_TLS_mutex);243}244245if (SDL_generic_TLS_mutex) {246SDL_DestroyMutex(SDL_generic_TLS_mutex);247SDL_generic_TLS_mutex = NULL;248}249}250251// Non-thread-safe global error variable252static SDL_error *SDL_GetStaticErrBuf(void)253{254static SDL_error SDL_global_error;255static char SDL_global_error_str[128];256SDL_global_error.str = SDL_global_error_str;257SDL_global_error.len = sizeof(SDL_global_error_str);258return &SDL_global_error;259}260261#ifndef SDL_THREADS_DISABLED262static void SDLCALL SDL_FreeErrBuf(void *data)263{264SDL_error *errbuf = (SDL_error *)data;265266if (errbuf->str) {267errbuf->free_func(errbuf->str);268}269errbuf->free_func(errbuf);270}271#endif272273// Routine to get the thread-specific error variable274SDL_error *SDL_GetErrBuf(bool create)275{276#ifdef SDL_THREADS_DISABLED277return SDL_GetStaticErrBuf();278#else279static SDL_TLSID tls_errbuf;280SDL_error *errbuf;281282errbuf = (SDL_error *)SDL_GetTLS(&tls_errbuf);283if (!errbuf) {284if (!create) {285return NULL;286}287288/* Get the original memory functions for this allocation because the lifetime289* of the error buffer may span calls to SDL_SetMemoryFunctions() by the app290*/291SDL_realloc_func realloc_func;292SDL_free_func free_func;293SDL_GetOriginalMemoryFunctions(NULL, NULL, &realloc_func, &free_func);294295errbuf = (SDL_error *)realloc_func(NULL, sizeof(*errbuf));296if (!errbuf) {297return SDL_GetStaticErrBuf();298}299SDL_zerop(errbuf);300errbuf->realloc_func = realloc_func;301errbuf->free_func = free_func;302SDL_SetTLS(&tls_errbuf, errbuf, SDL_FreeErrBuf);303}304return errbuf;305#endif // SDL_THREADS_DISABLED306}307308static bool ThreadValid(SDL_Thread *thread)309{310return SDL_ObjectValid(thread, SDL_OBJECT_TYPE_THREAD);311}312313void SDL_RunThread(SDL_Thread *thread)314{315void *userdata = thread->userdata;316int(SDLCALL *userfunc)(void *) = thread->userfunc;317318int *statusloc = &thread->status;319320// Perform any system-dependent setup - this function may not fail321SDL_SYS_SetupThread(thread->name);322323// Get the thread id324thread->threadid = SDL_GetCurrentThreadID();325326// Run the function327*statusloc = userfunc(userdata);328329// Clean up thread-local storage330SDL_CleanupTLS();331332// Mark us as ready to be joined (or detached)333if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) {334// Clean up if something already detached us.335if (SDL_GetThreadState(thread) == SDL_THREAD_DETACHED) {336SDL_free(thread->name); // Can't free later, we've already cleaned up TLS337SDL_free(thread);338}339}340}341342SDL_Thread *SDL_CreateThreadWithPropertiesRuntime(SDL_PropertiesID props,343SDL_FunctionPointer pfnBeginThread,344SDL_FunctionPointer pfnEndThread)345{346// rather than check this in every backend, just make sure it's correct upfront. Only allow non-NULL if Windows, or Microsoft GDK.347#if !defined(SDL_PLATFORM_WINDOWS)348if (pfnBeginThread || pfnEndThread) {349SDL_SetError("_beginthreadex/_endthreadex not supported on this platform");350return NULL;351}352#endif353354SDL_ThreadFunction fn = (SDL_ThreadFunction) SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, NULL);355const char *name = SDL_GetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, NULL);356const size_t stacksize = (size_t) SDL_GetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, 0);357void *userdata = SDL_GetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, NULL);358359if (!fn) {360SDL_SetError("Thread entry function is NULL");361return NULL;362}363364SDL_InitMainThread();365366SDL_Thread *thread = (SDL_Thread *)SDL_calloc(1, sizeof(*thread));367if (!thread) {368return NULL;369}370thread->status = -1;371SDL_SetAtomicInt(&thread->state, SDL_THREAD_ALIVE);372373// Set up the arguments for the thread374if (name) {375thread->name = SDL_strdup(name);376if (!thread->name) {377SDL_free(thread);378return NULL;379}380}381382thread->userfunc = fn;383thread->userdata = userdata;384thread->stacksize = stacksize;385386SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, true);387388// Create the thread and go!389if (!SDL_SYS_CreateThread(thread, pfnBeginThread, pfnEndThread)) {390// Oops, failed. Gotta free everything391SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);392SDL_free(thread->name);393SDL_free(thread);394thread = NULL;395}396397// Everything is running now398return thread;399}400401SDL_Thread *SDL_CreateThreadRuntime(SDL_ThreadFunction fn,402const char *name, void *userdata,403SDL_FunctionPointer pfnBeginThread,404SDL_FunctionPointer pfnEndThread)405{406const SDL_PropertiesID props = SDL_CreateProperties();407SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn);408SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);409SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata);410SDL_Thread *thread = SDL_CreateThreadWithPropertiesRuntime(props, pfnBeginThread, pfnEndThread);411SDL_DestroyProperties(props);412return thread;413}414415// internal helper function, not in the public API.416SDL_Thread *SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, size_t stacksize, void *userdata)417{418const SDL_PropertiesID props = SDL_CreateProperties();419SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) fn);420SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);421SDL_SetPointerProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, userdata);422SDL_SetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, (Sint64) stacksize);423SDL_Thread *thread = SDL_CreateThreadWithProperties(props);424SDL_DestroyProperties(props);425return thread;426}427428SDL_ThreadID SDL_GetThreadID(SDL_Thread *thread)429{430SDL_ThreadID id = 0;431432if (thread) {433if (ThreadValid(thread)) {434id = thread->threadid;435}436} else {437id = SDL_GetCurrentThreadID();438}439return id;440}441442const char *SDL_GetThreadName(SDL_Thread *thread)443{444if (ThreadValid(thread)) {445return SDL_GetPersistentString(thread->name);446} else {447return NULL;448}449}450451bool SDL_SetCurrentThreadPriority(SDL_ThreadPriority priority)452{453return SDL_SYS_SetThreadPriority(priority);454}455456void SDL_WaitThread(SDL_Thread *thread, int *status)457{458if (!ThreadValid(thread)) {459if (status) {460*status = -1;461}462return;463}464465SDL_SYS_WaitThread(thread);466if (status) {467*status = thread->status;468}469SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);470SDL_free(thread->name);471SDL_free(thread);472}473474SDL_ThreadState SDL_GetThreadState(SDL_Thread *thread)475{476if (!ThreadValid(thread)) {477return SDL_THREAD_UNKNOWN;478}479480return (SDL_ThreadState)SDL_GetAtomicInt(&thread->state);481}482483void SDL_DetachThread(SDL_Thread *thread)484{485if (!ThreadValid(thread)) {486return;487}488489// The thread may vanish at any time, it's no longer valid490SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);491492// Grab dibs if the state is alive+joinable.493if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_DETACHED)) {494SDL_SYS_DetachThread(thread);495} else {496// all other states are pretty final, see where we landed.497SDL_ThreadState thread_state = SDL_GetThreadState(thread);498if (thread_state == SDL_THREAD_DETACHED) {499return; // already detached (you shouldn't call this twice!)500} else if (thread_state == SDL_THREAD_COMPLETE) {501SDL_WaitThread(thread, NULL); // already done, clean it up.502}503}504}505506void SDL_WaitSemaphore(SDL_Semaphore *sem)507{508SDL_WaitSemaphoreTimeoutNS(sem, -1);509}510511bool SDL_TryWaitSemaphore(SDL_Semaphore *sem)512{513return SDL_WaitSemaphoreTimeoutNS(sem, 0);514}515516bool SDL_WaitSemaphoreTimeout(SDL_Semaphore *sem, Sint32 timeoutMS)517{518Sint64 timeoutNS;519520if (timeoutMS >= 0) {521timeoutNS = SDL_MS_TO_NS(timeoutMS);522} else {523timeoutNS = -1;524}525return SDL_WaitSemaphoreTimeoutNS(sem, timeoutNS);526}527528void SDL_WaitCondition(SDL_Condition *cond, SDL_Mutex *mutex)529{530SDL_WaitConditionTimeoutNS(cond, mutex, -1);531}532533bool SDL_WaitConditionTimeout(SDL_Condition *cond, SDL_Mutex *mutex, Sint32 timeoutMS)534{535Sint64 timeoutNS;536537if (timeoutMS >= 0) {538timeoutNS = SDL_MS_TO_NS(timeoutMS);539} else {540timeoutNS = -1;541}542return SDL_WaitConditionTimeoutNS(cond, mutex, timeoutNS);543}544545bool SDL_ShouldInit(SDL_InitState *state)546{547while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_INITIALIZED) {548if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED, SDL_INIT_STATUS_INITIALIZING)) {549state->thread = SDL_GetCurrentThreadID();550return true;551}552553// Wait for the other thread to complete transition554SDL_Delay(1);555}556return false;557}558559bool SDL_ShouldQuit(SDL_InitState *state)560{561while (SDL_GetAtomicInt(&state->status) != SDL_INIT_STATUS_UNINITIALIZED) {562if (SDL_CompareAndSwapAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED, SDL_INIT_STATUS_UNINITIALIZING)) {563state->thread = SDL_GetCurrentThreadID();564return true;565}566567// Wait for the other thread to complete transition568SDL_Delay(1);569}570return false;571}572573void SDL_SetInitialized(SDL_InitState *state, bool initialized)574{575SDL_assert(state->thread == SDL_GetCurrentThreadID());576577if (initialized) {578SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_INITIALIZED);579} else {580SDL_SetAtomicInt(&state->status, SDL_INIT_STATUS_UNINITIALIZED);581}582}583584585586