[Pyrex] acquiring the GIL?

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Feb 24 08:15:57 CET 2006


Victor Ng wrote:

> How do I properly write the pxd file to expose the pystate.h functions 
> to grab the GIL?
> 
> Do I have to translate PyAPI_FUNC and PyGILState_STATE into Pyrex 
> ctypedef declarations?

You can ignore PyAPI_FUNC, since it's just a macro used
to insert any weird C declaration stuff that your platform
might need. Pyrex doesn't need any such stuff.

PyGILState_STATE seems to be an enum, so something like
this should do:

   cdef extern from "pystate.h":
     enum PyGILState_STATE
     PyGILState_STATE PyGILState_Ensure()
     void PyGILState_Release(PyGILState_STATE)

Using them is a little tricky, since if there are any
Python variables used in between, Pyrex will insert
initialisation code for them *before* the call to
PyGILState_Ensure, where it's not safe to make
Python API calls. The best idea is probably to lift
everything between them out into another function,
i.e.

   cdef void someCallback(char *blah):
     cdef PyGILState_STATE state
     state = PyGILState_Ensure()
     callback_body(blah)
     PyGILState_Release(state)

   cdef void callback_body(char *blah):
     # do Python stuff

Now the whole of someCallback is pure C, and there
should be no problem.

But I haven't tested any of this, and there might
be some thread-related subtlety that will cause
it all to blow up, so use it at your own risk!

--
Greg




More information about the Pyrex mailing list