multi-thread python interpreaters and c++ program

myopc myopc at aaa.com
Tue Jun 9 01:50:47 EDT 2009


hi, all
  I am ruuning a c++ program (boost python) , which create many python 
interpreaters and each run a python script with use multi-thread 
(threading).
when the c++ main program exit, I want to shut down python interpreaters, 
but it crashed. I have googled a lot but cant get any clue.
here is my code, your suggestion will be greatly appreciated.

c++ :
/**** test multi interpreaters ***/
#include <Python.h>
#include <boost/python.hpp>
#include <boost/bind.hpp>
#include <string>
#include <windows.h>

using namespace boost::python;

static const char* strs[3]={
    "m1","m2","m3"
};
static void xxx(const char* abc){
    fprintf(stderr, "this is xxx %s\n", abc);
}

PyThreadState* testPy(int i){
    char buf[128];
    PyThreadState* ts = Py_NewInterpreter();

    object main_namespace = import("__main__").attr("__dict__");
    main_namespace["xxx"]= xxx;
    main_namespace["aaa"]= i+1;
    main_namespace["strs"]= strs[i];

    sprintf(buf, "execfile('pyinter/%d.py')",i+1);
    if(!PyRun_SimpleString(buf)){
        return ts;
    }else return 0;
}

int main(int argc, char** argv){
    PyThreadState *ts[3];
    Py_InitializeEx(0);
    PyEval_InitThreads();
    for(int i=0 ; i< 3; i++){
        ts[i]= testPy(i);
        if(! ts[i] ){
            printf("run %d error\n",i);
        } else {
            printf("run %d ok\n",i);
        }
    }

    PyEval_ReleaseLock(); /// release the lock, interpreaters run
    Sleep(3500);
    for(int i=0; i< 3; i++){
        if(! ts[i])continue;

        printf("delete %d  ", i);
        PyEval_AcquireThread(ts[i]);
        Py_Finalize();        ///shut down interpreaters ,crash here
        PyEval_ReleaseLock();
        Sleep(10);
        printf(" ok\n");
    }
Sleep(1500);
    printf("exit...\n");
}

each interpreater uses the same python script:

class MyTimer(object):
    def __init__(self, interval, function, args=[], kwargs={}):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs

    def start(self):
        self.stop()
        import threading
        self._timer = threading.Timer(self.interval, self._run)
        self._timer.setDaemon(True)
        self._timer.start()   ### start a python thread, keep running

    def restart(self):
        self.start()

    def stop(self):
        if self.__dict__.has_key("_timer"):
            self._timer.cancel()
            del self._timer

    def _run(self):
        try:
            self.function(strs)
        except:
            pass
        self.restart()

abc= MyTimer(aaa,xxx);
abc.start();








More information about the Python-list mailing list