Browse Source

Fixed memory leak when using detached threads

Fixes https://github.com/libsdl-org/SDL/issues/13886
Sam Lantinga 5 days ago
parent
commit
ede86a1267
1 changed files with 3 additions and 4 deletions
  1. 3 4
      src/thread/SDL_thread.c

+ 3 - 4
src/thread/SDL_thread.c

@@ -333,7 +333,7 @@ void SDL_RunThread(SDL_Thread *thread)
     // Mark us as ready to be joined (or detached)
     if (!SDL_CompareAndSwapAtomicInt(&thread->state, SDL_THREAD_ALIVE, SDL_THREAD_COMPLETE)) {
         // 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);
         }
@@ -487,11 +487,10 @@ void SDL_DetachThread(SDL_Thread *thread)
         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.
     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);
     } else {
         // all other states are pretty final, see where we landed.