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.
You code makes no sense in any version of Python:
PyEval_SaveThread/PyEval_RestoreThreadare for releasing and reacquiring the GIL in a Python-launched (created bythreadingmodule) thread (though you'd normally use thePy_BEGIN_ALLOW_THREADSandPy_END_ALLOW_THREADSmacros to simplify this).PyGILState_Ensure/PyGILState_Releaseare to allow threads not launched by Python'sthreadingmodule (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 thereforePyEval_SaveThreadcan'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.