8000 Release the GIL on shutdown only if it can be released · pythonnet/pythonnet@f5c24b0 · GitHub
[go: up one dir, main page]

Skip to content 65FC

Commit f5c24b0

Browse files
committed
Release the GIL on shutdown only if it can be released
Fixes an issue where there is no current thread state on shutdown. Also fixes a comment in Runtime.Initialize
1 parent b409a89 commit f5c24b0

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

src/runtime/runtime.cs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ internal static Version PyVersion
127127
/// <summary>
128128
/// Initialize the runtime...
129129
/// </summary>
130-
/// <remarks>When calling this method after a soft shutdown or a domain reload,
131-
/// this method acquires and releases the GIL. </remarks>
130+
/// <remarks>Always call this method from the Main thread. After the
131+
/// first call to this method, the main thread has acquired the GIL.</remarks>
132132
internal static void Initialize(bool initSigs = false, ShutdownMode mode = ShutdownMode.Default, bool fromPython = false)
133133
{
134134
if (_isInitialized)
@@ -414,8 +414,14 @@ internal static void Shutdown(ShutdownMode mode)
414414
// Some clr runtime didn't implement GC.WaitForFullGCComplete yet.
415415
}
416416
PyGILState_Release(state);
417-
// Then release the GIL for good.
418-
PyEval_SaveThread();
417+
// Then release the GIL for good, if there is somehting to release
418+
// Use the unchecked version as the checked version calls `abort()`
419+
// if the current state is NULL.
420+
if (_PyThreadState_UncheckedGet() != IntPtr.Zero)
421+
{
422+
PyEval_SaveThread();
423+
}
424+
419425
}
420426
else
421427
{
@@ -846,6 +852,9 @@ internal static unsafe long Refcount(IntPtr op)
846852
[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
847853
internal static extern IntPtr PyThreadState_Get();
848854

855+
[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
856+
internal static extern IntPtr _PyThreadState_UncheckedGet();
857+
849858
[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
850859
internal static extern IntPtr PyThread_get_key_value(IntPtr key);
851860

0 commit comments

Comments
 (0)
0