Fixed memory leak when using detached threads

Fixes https://github.com/libsdl-org/SDL/issues/13886

(cherry picked from commit ede86a1267)
This commit is contained in:
Sam Lantinga
2025-09-14 08:22:37 -07:00
parent 56507a6122
commit 11b8dd76db

View File

@@ -333,7 +333,7 @@ void SDL_RunThread(SDL_Thread *thread)
// Mark us as ready to be joined (or detached) // Mark us as ready to be joined (or detached)
if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) { if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) {
// Clean up if something already detached us. // Clean up if something already detached us.
if (SDL_GetThreadState(thread) == SDL_THREAD_DETACHED) { if (SDL_GetAtomicInt(&thread->state) == SDL_THREAD_DETACHED) {
SDL_free(thread->name); // Can't free later, we've already cleaned up TLS SDL_free(thread->name); // Can't free later, we've already cleaned up TLS
SDL_free(thread); SDL_free(thread);
} }
@@ -487,11 +487,10 @@ void SDL_DetachThread(SDL_Thread *thread)
return; return;
} }
// The thread may vanish at any time, it's no longer valid
SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);
// Grab dibs if the state is alive+joinable. // Grab dibs if the state is alive+joinable.
if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_DETACHED)) { if (SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_DETACHED)) {
// The thread may vanish at any time, it's no longer valid
SDL_SetObjectValid(thread, SDL_OBJECT_TYPE_THREAD, false);
SDL_SYS_DetachThread(thread); SDL_SYS_DetachThread(thread);
} else { } else {
// all other states are pretty final, see where we landed. // all other states are pretty final, see where we landed.