Addressing Incorrect Handling of Python GIL that Leads to a SEGFAULT #361
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I found what appears to be a bug in
bind/symbols.go
.Consider the following Go function that was generated by gopy:
This is generated for a Go method
ExampleFunction
of aGoObject
struct. The intent is for this method to be called from Python.The bug is that we access the C/Python API function
C.PyCallable_Check
before acquiring the GIL, leading to aSEGFAULT
. The problem lies in the following excerpt of the above function:Notice that we only acquire the GIL via
PyGILState_Ensure
after the call toC.PyCallable_Check(_fun_arg)
, which leads to aSEGFAULT
.The changes in this PR will result in the above Go function being generated differently as:
Notice that we now call
C.PyGILState_Ensure()
before the call toC.PyCallable_Check(_fun_arg)
. Likewise, we callC.PyGILState_Release(_gstate)
before returning within the body of the associated if-statement to ensure that there is a matching call (to match the_gstate := C.PyGILState_Ensure()
).In terms of testing, I've just been using the modified
gopy
in an application I'm developing. I'm in the process of doing more testing in the meantime; however, I am confident that this is a bug, as you must hold the Python GIL when interfacing/invoking any of the C/Python API.From the "Thread State and the Global Interpreter Lock" subsection of the "Initialization, Finalization, and Threads" Python C-API documentation:
On a separate (but related) note -- since we defer
C.PyEval_RestoreThread(_saved_thread)
at the beginning of the method's execution, it's a little silly to release the GIL viaC.PyGILState_Release(_gstate)
immediately before returning (even in the case where we don't call into Go code); however, we need to have matching calls betweenC.PyEval_SaveThread()
andC.PyEval_RestoreThread()
as well asPyGILState_Ensure()
andPyGILState_Release()
, so I think it ultimately makes sense to do things this way for now. In theory, we could provide more complex logic to handle the GIL more efficiently in the future.