[Twisted-Python] DeferredSemaphore - action on acquire and release

Jason Heeris jason.heeris at gmail.com
Mon Feb 7 18:23:04 MST 2011


I'm using a DeferredSemaphore with a token count of 1 to control
access to a serial port. I also have a GTK object for which I'd like
the "in-use" property to change (and notify listeners) when the
resource is in use. So far, I have something like this:

----
class SerialResource(gobject):

    # Property defs, etc

    def _acquire(self):
        # The "in-use" property is actually stored in self.taken
        self.taken = True
        self.notify('in-use')

    def _release(self, res):
        self.taken = False
        self.notify('in-use')
        return res

    def run(self, func, *args, **kargs):
        def wrapper():
            self._acquire()
            res = func(*args, **kargs)
            return res

        d = self.sem.run(wrapper)
        d.addBoth(self._release)
        return d
----

I feel like there might be a simpler way to do this, but I just can't
see it. Or is this as simple as I can make it?

— Jason




More information about the Twisted-Python mailing list