[Twisted-Python] Lock class using Deferreds

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

On Fri, Mar 05, 2004 at 11:19:01AM -0500, Itamar Shtull-Trauring wrote:
class Lock: """A lock for event driven systems."""
I have very very similiar looking code on my harddisk... what inspired you to write this? :)
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)
In my version, I had a 'throttle' instance attribute: d = self.queue.pop(0) if self.throttle: reactor.callLater(0, d.callback, self) else: d.callback(self) Considering I never actually *used* my version, this might be a premature feature addition, though.
def _releaseAndReturn(self, r): self.release() return r
I wonder if this convenience function should also call log.err if isinstance(r, failure.Failure)? But that's probably just premature featuritus again :) So, where in Twisted is a good spot for it? twisted.internet.util? -Andrew.

Andrew Bennetts wrote:
On Fri, Mar 05, 2004 at 11:19:01AM -0500, Itamar Shtull-Trauring wrote:
class Lock: """A lock for event driven systems."""
I have very very similiar looking code on my harddisk... what inspired you to write this? :)
I have something vaguely similar too; a class that handled a 'pipeline' (?) of Deferreds and didn't allow more than N at a time. My purpose for it was doing several thousand DNS queries and I only wanted at most N outstanding requests at a time, so I wouldn't overload the servers. Ok, so it's not that similar, but it's something that would probably go in the same module ;-) -- Twisted | Christopher Armstrong: International Man of Twistery Radix | Release Manager, Twisted Project ---------+ http://radix.twistedmatrix.com/
participants (3)
-
Andrew Bennetts
-
Christopher Armstrong
-
Itamar Shtull-Trauring