Embedded python with threads

nik my.news.groups at noos.fr
Thu Sep 16 03:52:45 EDT 2004


nik wrote:
> hi,
> 
> I have a C++ app that loads a python module and calls a function from 
> it. The call is getting the contents of a list that's global in that 
> module.
> 
> However, I'd like the python script to be also running a thread that 
> fills that global list, but can't figure out how to do it. Essentially 
> the code looks like;
> 
> in the C++ app;
> 
> ////
> Py_Initialize();
> 
> // PyImport_ImportModule blocks until the myModule script has run
> // through...
> PyObject* module = PyImport_ImportModule("myModule");
> 
> PyObject* function = PyObject_GetAttrString(module, "GetList");
> while(1) {
>     PyObject* pyList = PyObject_CallFunction(function, "");
>     // use the stuff in pyList
>     sleep(15);
>     }
> ////
> 
> and in the myModule.py;
> 
> ####
> import thread
> import time
> orderListLock = thread.allocate_lock()
> 
> pyList = []
> 
> def GetList():
>     global pyList
>     tmpList = []
>     orderListLock.acquire()
>     tmpList = pyList
>     orderListLock.release()
>     return tmpList
> 
> def keepFillingListThread():
>     global pyList
>     while 1:
>         orderListLock.acquire()
>         pyList.append(somestuff)
>         orderListLock.release()
>         time.sleep(5)
> 
> # the following statement happens when the C++ app imports the module,
> # but the thread only lives as long the main python thread (which is
> # over straight away on my linux PC)
> 
> thread.start_new_thread(keepFillingListThread, ())
> 
> ####
> 
> Has anyone any ideas?
> 
> thanks,
> nik

Hi again,

I think I'm one step further. I've put the 
thread.start_new_thread(keepFillingListThread, ()) command into its own 
function, like

def startThreads():
	thread.start_new_thread(keepFillingListThread, ())
	while 1:
		pass

and then in the C++ part, I've used boost::thread to create a thread to 
call startThreads like;

void myBoostThread::operator () ()
{
	PyObject* function = PyObject_GetAttrString(m_cfg.module, "createThreads");
	PyObject* result = PyObject_CallFunction(function, "");
}

// after the PyObject* module = PyImport_ImportModule("myModule"); line 
from above:
myBoostThreadParams params;
params.module = module;
myBoostThread mythread(params);
boost::thread theThread(mythread);

this seems to work (at least, the python threads stay alive), but it 
rapidly crashes out with

Fatal Python error: ceval: tstate mix-up
Aborted

as soon as I call the function GetList above.

Can anyone help me?

thanks



More information about the Python-list mailing list