Hi,

I'm running in to problems with the __dealloc__ method of extension
types.  Specifically, I need to acquire a Python lock inside a
__dealloc__ method in order to free resources which come from an
external C library.  The code is something like:

def __dealloc__(self):
    mylock.acquire()
    try:
        free_resource(self.id)
    finally:
        mylock.release()

In this code, free_resource is an external C function, and self.id is a
C attribute of the extension type (not a Python attribute).

This works fine in single-threaded code, but leads to random
segmentation faults when using threads, apparently when the garbage
collector runs.  Commenting out mylock.acquire() and mylock.release()
fixes the segmentation fault.

Is the GIL guaranteed to be held when __dealloc__ is called?  In other
words, is it safe to call into Python?  If not, is there an approved
Cython way to explicitly acquire the GIL?  There is unfortunately no way
to get rid of the lock, as the C library I'm interfacing with is not
thread-safe and if free_resource is called the wrong number of times
very bad things will happen.

Alternatively, is there another (safer) method I can use for extension
types, analagous to Python's __del__ method?

Thanks,
Andrew Collette

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to