Embedded MacPython in a Multi-Threaded App

Bill Orcutt b_orcutt at pobox.com
Mon Apr 7 19:00:10 EDT 2003


Hi-

I'm writing an C application for OS 9 and I need/want to call some
python
code from inside of an MP Task Thread. Possible? I've had a look at
the official
Python thread documentation and googled and gleaned as much as I can
from
the web, but I still have yet find something that works.

In my main thread I intialize python and threads--

<<

    PyMac_Initialize();
    PyEval_InitThreads();
    
    // save a pointer to the main PyThreadState object
    mainThreadState = PyThreadState_Get();
    // release the lock
    PyEval_ReleaseLock();

>>

and then in my worker thread call--

<<

    PyEval_AcquireLock();
    // get a reference to the PyInterpreterState
    mainInterpreterState = mainThreadState->interp;
    // create a thread state object for this thread
    myThreadState = PyThreadState_New(mainInterpreterState);
    // free the lock
    PyEval_ReleaseLock();

    // grab the global interpreter lock
    PyEval_AcquireLock();
    // swap in my thread state
    PyThreadState_Swap(myThreadState);
    
    // execute some python code
        PyRun_SimpleString("print 'howdy-doo'"); //python here

    // clear the thread state
    PyThreadState_Swap(NULL);
    // release our hold on the global interpreter
    PyEval_ReleaseLock();

    // grab the lock
    PyEval_AcquireLock();
    // swap my thread state out of the interpreter
    PyThreadState_Swap(NULL);
    // clear out any cruft from thread state object
    PyThreadState_Clear(myThreadState);
    // delete my thread state object
    PyThreadState_Delete(myThreadState);
    // release the lock
    PyEval_ReleaseLock();

>>

after the worker thread exits I finalize and clean up in the main
thread.

I've tried every permutation on this I could come up with, including a
<<Py_BEGIN_ALLOW_THREADS>> block and bracketing the python call with
<<MPEnterCriticalRegion>>. Also have had a look at pysvr.c,
pythonrun.c & ceval.c.

Clearly I'm flying blind. Any assistance or tips would be greatly
appreciated.

thanks

Bill




More information about the Python-list mailing list