Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

python thread state

29 views
Skip to first unread message

Bryan

unread,
Oct 23, 2006, 9:32:07 AM10/23/06
to pytho...@python.org
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

Stefan Schukat

unread,
Oct 24, 2006, 7:05:09 AM10/24/06
to bel...@gmail.com, pytho...@python.org
For this use case the PyGILState API was introduced.

e.g. try
PyGILState_STATE state = PyGILState_Ensure()
run python code
PyGILState_Release(state)

Stefan

> --
> http://mail.python.org/mailman/listinfo/python-list
>

0 new messages