Understanding PyEval_InitThreads

Martin v. Loewis martin at v.loewis.de
Wed Nov 20 03:41:10 EST 2002


Thomas Heller <theller at python.net> writes:

> 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();
> }

I suggest a simpler strategy:

   pts = PyThreadState_New(g_interp);
   if (!pts)
       Py_FatalErorr(...);
   PyEval_AcquireThread(pts);
   /* call Python functions */
   PyEval_ReleaseThread(pts);
   PyThreadState_Clear(pts);
   PyThreadState_Delete(pts);

> 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?

I'm not quite sure why you don't have to call it on Windows; I would
expect it to crash there as well. You can call PyEval_InitThreads as
many times as you want.

Regards,
Martin




More information about the Python-list mailing list