[Pythonmac-SIG] MP Task Threads and Embedded Python

Bill Orcutt mailing-l@pobox.com
Sun, 06 Apr 2003 20:53:16 -0800


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. 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>>

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

thanks

Bill

PS- I saw it suggested somewhere that threading is not enabled by default in
MacPython- true?