Understanding PyEval_InitThreads
Thomas Heller
theller at python.net
Wed Nov 20 02:56:09 EST 2002
I had already posted this under a different subject, this is a more detailed
description of the problem (and my question):
When porting an extension from Windows to Linux, I got crashes when
C code calls back into Python.
Here's what I'm doing:
Py_BEGIN_ALLOW_THREAD
call_some_c_code()
Py_END_ALLOW_THREAD
The call_some_c_code() function calls back into Python, so I have to
acquire the interpreter lock again, and create a new threadstate in
the callback. Note that g_interp is initialized when the extension
module is loaded:
static PyInterpreterState *g_interp;
void call_back_into_python(void)
{
PyThreadState *pts;
PyEval_AcquireLock();
pts = PyThreadState_New(g_interp);
if (!pts)
Py_FatalErorr(...);
if (NULL != PyThreadState_Swap(pts)
Py_FatalError(...);
/* now call Python functions */
pts = PyThreadState_Swap(NULL);
if (!pts)
Py_FatalError(...);
PyThreadState_Clear(pts);
PyThreadState_Delete(pts);
PyEval_ReleaseLock();
}
The crash occurred in the PyEval_AcquireLock() function, and it worked
fine when I added a call to PyEval_InitThread() at module load time.
This was unneeded on Windows, I assume because on Windows
PyEval_InitThreads() has been called before. My question is: why do I
have to call this function on Linux, but not on Windows? Does it do
any harm if I call the function when the ctypes module is loaded, or
should I wait until the callbacks are actually needed?
Thomas
More information about the Python-list
mailing list