[Python-Dev] GIL vs thread state (original) (raw)

Thomas Heller theller@python.net
14 Apr 2003 14:06:39 +0200


The docs for PyThreadState_Clear() state that the interpreter lock must be held.

I had this code in ctypes to delete the thread state and release the lock:

static void LeavePython(char *msg) { PyThreadState *pts = PyThreadState_Swap(NULL); if (!pts) Py_FatalError("wincall (LeavePython): ThreadState is NULL?"); PyThreadState_Clear(pts); PyThreadState_Delete(pts); PyEval_ReleaseLock(); }

and (under certain coditions, when ptr->frame was not NULL), got "Fatal Python error: PyThreadState_Get: no current thread" in the call to PyThreadState_Clear().

The GIL is held while this code is executed, although there is no thread state. Changing the code to the following fixes the problem, it seems holding the GIL is not enough:

static void LeavePython(char *msg) { PyThreadState *pts = PyThreadState_Get(); if (!pts) Py_FatalError("wincall (LeavePython): ThreadState is NULL?"); PyThreadState_Clear(pts); pts = PyThreadState_Swap(NULL); PyThreadState_Delete(pts); PyEval_ReleaseLock(); }

Is this a documentation problem, or a misunderstanding on my side? And, while we're on it, does the second version look ok?

Thomas