Skip to content

Grab the GIL on shutdown when checking for exceptions #1832

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/runtime/PythonEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Comment on lines +361 to +366
Copy link
Member

@lostmsu lostmsu Jun 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Py.GIL() no longer tries to force runtime initialization, I think the code would be easier to read with a simple using (Py.GIL()) { ... } around the if.

I don't think it is necessary to check if we are hosted in Python. Runtime.Shutdown further down does not.

Copy link
Member

@lostmsu lostmsu Jun 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another issue is that the code below throws when Python error is set. And that throw prevents the GIL release code to be reached making the GIL unreleasable. Would not be a problem with using Py.GIL

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll adjust it accordingly s.t. we can tag rc1.

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;
Expand Down