segfault when calling Python from C thread

Greg Chapman glc at well.com
Mon Feb 21 09:13:35 EST 2005


Fredrik Lundh wrote:

> Greg Chapman wrote:
> 
> > Your callback function needs to hold the Python GIL (and have a
> > vaild threadstate) before it calls any Python C-API functions.
> > Change the last part of it to:
> > 
> >    PyGILState_STATE state;
> > 
> >    /* ... */
> > 
> >    /* Time to call the callback */
> > 
> >    state = PyGILState_Ensure();
> > 
> >    arglist = Py_BuildValue("(s)", str);
> >    result = PyEval_CallObject(my_callback, arglist);
> >    Py_DECREF(arglist);
> >    if(result == NULL)
> >        return;
> >    Py_DECREF(result);
> > 
> >    PyGILState_Release(state);
> > }
> 
> you might wish to make sure you release the GIL even if the callback
> raises an exception...
> 
> </F> 

Argh, thanks for catching that.  You probably put that too politely
though (in case anyone sees this who might think that is optional): one
should absolutely make sure all code paths which call PyGILState_Ensure
have a matching call to PyGILState_Release.

---
Greg Chapman



More information about the Python-list mailing list