From 0534d7f3c9864336e018ae366c6f3295c8402e9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Bourbonnais?= Date: Thu, 23 Jun 2022 15:33:29 -0400 Subject: [PATCH] Grab the GIL on shutdown when checking for exceptions The GIL isn't taken when being called from the DomainUnload handler. --- src/runtime/PythonEngine.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/runtime/PythonEngine.cs b/src/runtime/PythonEngine.cs index f184ebe88..5d1069db0 100644 --- a/src/runtime/PythonEngine.cs +++ b/src/runtime/PythonEngine.cs @@ -355,12 +355,26 @@ public static void Shutdown() { return; } + + // If we're embedded, we need to take the GIL, if it wasn't already + // taken, as we may get called from the DomainUnload handler. + var pyGILState = PyGILState.PyGILState_UNLOCKED; + if (!Runtime.HostedInPython) + { + pyGILState = Runtime.PyGILState_Ensure(); + } + if (Exceptions.ErrorOccurred()) { throw new InvalidOperationException( "Python error indicator is set", innerException: PythonException.PeekCurrentOrNull(out _)); } + + if (!Runtime.HostedInPython) + { + Runtime.PyGILState_Release(pyGILState); + } // If the shutdown handlers trigger a domain unload, // don't call shutdown again. AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload;