Added TLS initialization and shutdown functions

Fixes https://github.com/libsdl-org/SDL/issues/8576
This commit is contained in:
Sam Lantinga
2024-07-11 10:38:40 -07:00
parent f0ceb92dca
commit b517043936
8 changed files with 171 additions and 67 deletions

View File

@@ -29,27 +29,27 @@
static pthread_key_t thread_local_storage = INVALID_PTHREAD_KEY;
static SDL_bool generic_local_storage = SDL_FALSE;
SDL_TLSData *SDL_SYS_GetTLSData(void)
void SDL_SYS_InitTLSData(void)
{
if (thread_local_storage == INVALID_PTHREAD_KEY && !generic_local_storage) {
static SDL_SpinLock lock;
SDL_LockSpinlock(&lock);
if (thread_local_storage == INVALID_PTHREAD_KEY && !generic_local_storage) {
pthread_key_t storage;
if (pthread_key_create(&storage, NULL) == 0) {
SDL_MemoryBarrierRelease();
thread_local_storage = storage;
} else {
generic_local_storage = SDL_TRUE;
}
if (pthread_key_create(&thread_local_storage, NULL) != 0) {
thread_local_storage = INVALID_PTHREAD_KEY;
SDL_Generic_InitTLSData();
generic_local_storage = SDL_TRUE;
}
SDL_UnlockSpinlock(&lock);
}
}
SDL_TLSData *SDL_SYS_GetTLSData(void)
{
if (generic_local_storage) {
return SDL_Generic_GetTLSData();
}
SDL_MemoryBarrierAcquire();
return (SDL_TLSData *)pthread_getspecific(thread_local_storage);
if (thread_local_storage != INVALID_PTHREAD_KEY) {
return (SDL_TLSData *)pthread_getspecific(thread_local_storage);
}
return NULL;
}
int SDL_SYS_SetTLSData(SDL_TLSData *data)
@@ -57,8 +57,22 @@ int SDL_SYS_SetTLSData(SDL_TLSData *data)
if (generic_local_storage) {
return SDL_Generic_SetTLSData(data);
}
if (pthread_setspecific(thread_local_storage, data) != 0) {
return SDL_SetError("pthread_setspecific() failed");
}
return 0;
}
void SDL_SYS_QuitTLSData(void)
{
if (generic_local_storage) {
SDL_Generic_QuitTLSData();
generic_local_storage = SDL_FALSE;
} else {
if (thread_local_storage != INVALID_PTHREAD_KEY) {
pthread_key_delete(thread_local_storage);
thread_local_storage = INVALID_PTHREAD_KEY;
}
}
}