SDL: cocoa: Make sure GL context destruction happens on the main thread.

From 344546b4ea79a070e8b6bcccab542551ab5bdf55 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Thu, 24 Oct 2024 14:53:16 -0400
Subject: [PATCH] cocoa: Make sure GL context destruction happens on the main
 thread.

Fixes #10900.
---
 src/video/cocoa/SDL_cocoaopengl.m | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/src/video/cocoa/SDL_cocoaopengl.m b/src/video/cocoa/SDL_cocoaopengl.m
index 29f1a66e07262..cacfbb873a04e 100644
--- a/src/video/cocoa/SDL_cocoaopengl.m
+++ b/src/video/cocoa/SDL_cocoaopengl.m
@@ -523,13 +523,31 @@ bool Cocoa_GL_SwapWindow(SDL_VideoDevice *_this, SDL_Window *window)
     }
 }
 
-bool Cocoa_GL_DestroyContext(SDL_VideoDevice *_this, SDL_GLContext context)
+static void DispatchedDestroyContext(SDL_GLContext context)
 {
     @autoreleasepool {
         SDL3OpenGLContext *nscontext = (__bridge SDL3OpenGLContext *)context;
         [nscontext cleanup];
         CFRelease(context);
     }
+}
+
+bool Cocoa_GL_DestroyContext(SDL_VideoDevice *_this, SDL_GLContext context)
+{
+    if ([NSThread isMainThread]) {
+        DispatchedDestroyContext(context);
+    } else {
+        if (SDL_opengl_async_dispatch) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+              DispatchedDestroyContext(context);
+            });
+        } else {
+            dispatch_sync(dispatch_get_main_queue(), ^{
+              DispatchedDestroyContext(context);
+            });
+        }
+    }
+
     return true;
 }