static PyObject *foo(PyObject *self, PyObject* args) { Py_BEGIN_ALLOW_THREADS // do python internel stuff Py_END_ALLOW_THREADS return PyInt_FromLong(99L); } int main(int argc, char **argv) { // initializes python and modules InitPython(); PyThreadState * mainThreadState = PyEval_SaveThread(); // release the lock PyEval_ReleaseLock(); // get the global lock PyEval_AcquireLock(); // get a reference to the PyInterpreterState PyInterpreterState * mainInterpreterState = mainThreadState->interp; // create a thread state object for this thread PyThreadState * 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 // start threaded python code // ... // 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(); PyEval_AcquireLock(); PyThreadState_Swap(myThreadState); Py_Finalize(); }