SDL: Reduce the possibility of SDL_LockMutex getting called on a destroyed mutex after SDL_StopEventLoop

From 6e0df0af24a0f6edabbbf01421da494c4738a3ec Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Thu, 19 Dec 2024 09:32:31 -0800
Subject: [PATCH] Reduce the possibility of SDL_LockMutex getting called on a
 destroyed mutex after SDL_StopEventLoop

---
 src/events/SDL_events.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/src/events/SDL_events.c b/src/events/SDL_events.c
index 50e02200381a7..c68dbc126cbd7 100644
--- a/src/events/SDL_events.c
+++ b/src/events/SDL_events.c
@@ -886,12 +886,17 @@ void SDL_StopEventLoop(void)
     }
     SDL_zero(SDL_EventOK);
 
-    SDL_UnlockMutex(SDL_EventQ.lock);
-
+    SDL_Mutex *lock = NULL;
     if (SDL_EventQ.lock) {
-        SDL_DestroyMutex(SDL_EventQ.lock);
+        lock = SDL_EventQ.lock;
         SDL_EventQ.lock = NULL;
     }
+
+    SDL_UnlockMutex(lock);
+
+    if (lock) {
+        SDL_DestroyMutex(lock);
+    }
 }
 
 // This function (and associated calls) may be called more than once