[Twisted-Python] Lock class using Deferreds

Itamar Shtull-Trauring itamar at itamarst.org
Fri Mar 5 09:19:01 MST 2004


class Lock:
    """A lock for event driven systems."""

    def __init__(self):
        self.waiting = []
        self.locked = 0

    def acquire(self):
        """Attempt to acquire the lock.

        @return Deferred which returns on lock acquisition.
        """
        d = defer.Deferred()
        if self.locked:
            self.waiting.append(d)
        else:
            self.locked = 1
            d.callback(self)
        return d

    def release(self):
        """Release the lock.

        Should be called by whoever did the acquire() when the shared
        resource is free.
        """
        assert self.locked
        self.locked = 0
        if self.waiting:
            # someone is waiting to acquire lock
            self.locked = 1
            d = self.waiting.pop(0)
            d.callback(self)

    def _releaseAndReturn(self, r):
        self.release()
        return r
    
    def run(self, f, *args, **kwargs):
        """Acquire lock, run function, release lock.

        @return Deferred of function result.
        """
        d = self.acquire()
        d.addCallback(lambda r: defer.maybeDeferred(f, *args, **kwargs).addBoth(self._releaseAndReturn))
        return d

-- 
Itamar Shtull-Trauring    http://itamarst.org
Looking for a job: http://itamarst.org/resume.html





More information about the Twisted-Python mailing list