Issue with GIL on Python 3.12.2

76 views Asked by At

I am using this code:

PyThreadState * thread = PyEval_SaveThread();
PyGILState_STATE gil = PyGILState_Ensure();

// ...

PyGILState_Release(gil);
PyEval_RestoreThread(thread);

In Python 3.11.8 it works well, but when I switched version to 3.12.2, my application is crashing on the first variable, error message is:

Fatal Python error: the function must be called with the GIL held, after Python initialization and before Python finalization, but the GIL is released (the current Python thread state is NULL)

What is the problem and how can I fix? I know that some changes were introduced between 3.11 and 3.12 with GIL but I did not find any informations about issue that I have.

1

There are 1 answers

0
ShadowRanger On

You code makes no sense in any version of Python:

  • PyEval_SaveThread/PyEval_RestoreThread are for releasing and reacquiring the GIL in a Python-launched (created by threading module) thread (though you'd normally use the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros to simplify this).

  • PyGILState_Ensure/PyGILState_Release are to allow threads not launched by Python's threading module (and therefore lacking GIL state) to acquire the GIL prior to calling into Python level code.

Your error indicates you've either already released the GIL, or possible you're in a non-threading-created thread, and therefore PyEval_SaveThread can't be called (you're trying to save thread state that doesn't exist, because it's a not the active Python thread). You need to know which type of thread you are, and use only the GIL-management APIs associated with that type of thread (and definitely not release the GIL twice or the like).

I strongly suggest reading the API docs for threading to help understand the APIs you're calling.