Help!: Embedding python in a multithreaded application

Rafael Garcia tilah78 at hotmail.com
Fri Jul 19 14:16:30 EDT 2002


Hello. 
I'm working in a project in C++ in which I'm required to embed a python
interpreter. For that I have made a python/C module that works as a
wrapper to my c++ classes. The project is multithreaded and one of my C
threads calls python code through the python/C API when some event occurs.


When I execute my python scripts -that register a callback function for an
event and call functions in my module that throw events- in my interpreter
sometimes an exception that most of the time is "Fatal Python error:
ceval: orphan tstate" is thrown. If I don't use the callback functions the
scripts run well so the problem is in the way multiple threads access the
python interpreter. 

I use the following snip of code (as readed in the documentation): 

void OnEventX(...) 
{ 
   PyThreadState *tstate; 
   tstate = PyThreadState_New(mainThreadState->interp); 
   PyEval_AcquireThread(tstate); 

   PyObject *arglist; 
   PyObject *result; 

   arglist = Py_BuildValue(...); 
   result = PyEval_CallObject(CallbackFunc_OnEventX, arglist); 
   Py_XDECREF(result); 
   Py_XDECREF(arglist); 

   PyThreadState_Clear(tstate); 
   PyThreadState_DeleteCurrent(); 
} 

There are more pieces of code like the later in my module, one for each
event my system can throw. 
The global variable mainThreadState is a PyThreadState object that was
filled using the function PyThreadState_Get() in the main() function in my
program.

Could you tell me what I'm doing wrong?. Is it a bug?. Could you tell me
how should I make a multithreaded python interpreter? The documentation
about this is very poor. 

I use version 2.2.1 Python binaries under Windows XP. I'm working with MS
Visual C++ 6.0. 

Thanks for your attention. 
  Rafael Garcia, tilah78 at hotmail.com





More information about the Python-list mailing list