Py_NewInterpreter and PyGILState API

Christoph Wiedemann wiedeman at
Mon Sep 20 15:43:49 CEST 2004


i have some trouble to understand the Py_NewInterpreter API function. The
docs state, that Py_NewInterpreter returns a new PyThreadState instance. One
can switch between interpreters by swapping thread states. I've used that,
and it worked well, until i decided to use the PyGILState_* API functions.

After digging a while, i found, that these functions assume, that there is
only one PyThreadState instance per thread. However, this doesn't play nice
with using the Py_NewInterpreter function, which always returns a new thread
state (as i understand it), even if used in a single-threaded application.

I'm wondering, why Py_NewInterpreter does actually return a PyThreadState
pointer instead of a PyInterpreterSate pointer?

My current solution uses the following code to swap between interpreters:

// i hold an 'is' variable for each interpreter i need:
PyInterpreterState *is = Py_NewInterpreter()->interp;

// to switch to a specific interpreter:
PyGILState_STATE gilState = PyGILState_Ensure();
PyThreadState_Get()->interp = is;
// use python API

This code seems to work fine, but one issue remains: I can't use

PyGILState_STATE gilState = PyGILState_Ensure();

I get the following error: "Fatal Python error: Py_EndInterpreter: not the
last thread". I guess this is due to the fact that i throw away the
PyThreadState returned by Py_NewInterpreter ?

Thanks in advance,

More information about the Python-list mailing list