Need some help with Python/C api and threading

Thomas Heller theller at
Thu Jun 17 17:58:46 CEST 2004

>>>>>> "Steve" == Steve Menard <steve.menard at> writes:
>     Steve> Here is my problem.  I have this library thats hosts
>     Steve> another language within python, and allows that language to
>     Steve> call back INTO python.
>     Steve> All is good as long as the other languages calls back on
>     Steve> the same thread. If the callback arrives on a different
>     Steve> thread, all hell break loose and the program dies horribly.
>     Steve> looking at the C api documentation, I came upon the
>     Steve> following block of code :
>     Steve>      PyThreadState *tstate; PyObject *result;
>     Steve>      /* interp is your reference to an interpreter
>     Steve> object. */ tstate = PyThreadState_New(interp);
>     Steve> PyEval_AcquireThread(tstate);
>     Steve>      /* Perform Python actions here.  */ result =
>     Steve> CallSomeFunction(); /* evaluate result */
>     Steve>      /* Release the thread. No Python API allowed beyond
>     Steve> this point. */ PyEval_ReleaseThread(tstate);
>     Steve>      /* You can either delete the thread state, or save it
>     Steve> until you need it the next time. */
>     Steve> PyThreadState_Delete(tstate);
>     Steve> Which would seem to be what I need. However, I have no idea
>     Steve> how to get at that interp pointer. I tried the following :
>     Steve> 		PyInterpreterState* interp =
>     Steve> PyInterpreterState_New(); PyThreadState *tstate =
>     Steve> PyThreadState_New(interp); PyEval_AcquireThread(tstate);
>     Steve> but then it crashes on the second line ...
>     Steve> Anybody ever done this? As a side note, the hosted language
>     Steve> can start an arbitrary number of threads ...
>     Steve> Steve

If your library is a Python extension, you should get and save the
PyInterpreterState in the initxxx() function, which initializes the

If using Python 2.3 you could (should?) probably use the
PyGILState_Ensure() and PyGILState_Release() functions, which manage all
this for you.  See PEP311

Maybe also it is needed to call PyEval_InitThreads() somewhere in the
init function.


More information about the Python-list mailing list