[capi-sig] PyGILState_Ensure/PyGILState_Release

Bob Rossi bob at brasko.net
Wed Jun 27 18:24:19 CEST 2012


Hi,

I'm really having trouble understanding the python threading model.

It's clear to me from the docs,
  http://docs.python.org/py3k/c-api/init.html?highlight=initthread
that I need to initialize python as so when requiring the use of
threads,
  Py_Initialize();
  PyEval_InitThreads();

Then, after that point, in each new thread, I should use
  PyGILState_STATE state = PyGILState_Ensure();
  // python code
  PyGILState_Release(state);

A few questions arise which do not seem to be documented clearly.

It's not clear to me if a call to Ensure locks python into
executing only in that thread until Release is called, or if it's just
a registration function which then allows python to choose which
python code it would like to execute in which thread at which time.
Can anyone answer this?

Based on my confusion above, I'm wondering if I can
wrap the Ensure/Release calls around the entire new thread,
or should this be done around a small snippet of python code?
What are the trade offs?

Finally, I notice that after my call to PyEval_InitThreads() I
had to call
  PyEval_SaveThread();
in order to allow other threads to call PyGILState_Ensure() with
out blocking forever. This is not documented. I'm not sure I'm
doing the correct thing here. Any ideas?

Thanks,
Bob


More information about the capi-sig mailing list