python thread state

Bryan belred at gmail.com
Mon Oct 23 09:32:07 EDT 2006


hi,

i'm trying to write a multithreaded embedded python application and i'm
having some trouble.  i found this article "embedding python in
multi-threaded c/c++ applications" in the python journal
(http://www.linuxjournal.com/article/3641) but there still seems to be a
step missing for me.

each time a function in my c module is called, it's called on a different c
thread.  i would then like to call a function in an embedded python script.
from my understanding of the article, you can associate a python script
with a c thread by calling PyThreadState_New as in this code:

// save main thread state
PyThreadState * mainThreadState = NULL;
mainThreadState = PyThreadState_Get();
PyEval_ReleaseLock();

// setup for each thread
PyEval_AcquireLock();
PyInterpreterState * mainInterpreterState = mainThreadState->interp
PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState);
PyEval_ReleaseLock();

//execute python code
PyEval_AcquireLock();
PyThreadState_Swap(myThreadState);
# execute python code
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();


unfortunately, this doesn't work for me because each time i get called to
execute python code, i'm in a new c thread and PyThreadState_Swap seems to
want to be executed in the same c thread that PyThreadState_New was
executed in.  if this isn't the case, please let know.  

i then called PyThreadState_New each time i wanted to call a python function
in the script, but PyThreadState_New wipes out, or rather gives you a new
global dictionary, because i lost all my global variables.  the article
assumes you have one c thread per python thread state, but i want multiple
c threads per python thread state. Is there a c api function that will
associate a c thread without resetting the global dictionary?

thank you,

bryan




More information about the Python-list mailing list