Py_NewInterpreter and PyGILState API

  • Thread starter Christoph Wiedemann
  • Start date
C

Christoph Wiedemann

Hello,

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
PyGILState_Release(gilState);

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

PyGILState_STATE gilState = PyGILState_Ensure();
Py_EndInterpreter(PyThreadState_Get());
PyGILState_Release(gilState);

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,
Christoph
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,208
Latest member
RandallLay

Latest Threads

Top