[capi-sig] Question about proper GIL management for a language interoperability tool

Jack Jansen Jack.Jansen at cwi.nl
Sat Jan 12 18:28:26 CET 2008


On 11-Jan-2008, at 19:14 , Tom Epperly wrote:
> CASE 1 (some other language calling Python via C)
> ========================================
> foo_Factorial(struct foo_t *self, int32_t arg) {
>  /* C routine that calls Python */
>  PyGILState_STATE _gstate;
>  _gstate = PyGILState_Ensure();
>  /* convert incoming arguments from C to Python */
>  _result = PyObject_CallObject(_pfunc, _args);
>  /* process outgoing arguments or exceptions */
>  PyGILState_Release(_gstate);
>  /* return to caller in whatever language */
> }

This is what I always do too.

> CASE 2 (Python calling some other language via C)
> ========================================
> static PyObject *
> pStub_foo_Factorial(PyObject *_self, PyObject *_args, PyObject  
> *_kwdict) {
>  PyObject *result;
>  /* unpack incoming Python arguments into their C equivalents */
>  Py_BEGIN_ALLOW_THREADS
>  /* dispatch to method implementation */
>  foo_Factorial(i,k,l); /* this step is actually done through a  
> function
> pointer */
>  Py_END_ALLOW_THREADS
>  /* pack outgoing C arguments into the Python return value  or process
> any exceptions */
>  return result;
> }


Here I use
	PyThreadState *_save = PyEval_SaveThread();
	...
	PyEval_RestoreThread(_save);
But that pretty much amounts to the same, I think, modulo C  
preprocessor trickery (which got in my way because I'm working in C++).

This module does serious multithreaded nesting from Python to C++ to  
Python to C++ etc etc etc, and I haven't yet run into a problem.
--
Jack Jansen, <Jack.Jansen at cwi.nl>, http://www.cwi.nl/~jack
If I can't dance I don't want to be part of your revolution -- Emma  
Goldman




More information about the capi-sig mailing list