[Twisted-Python] Lock class using Deferreds

Andy Gayton andy at thecablelounge.com
Fri Mar 5 19:47:17 MST 2004


 >> On Fri, 05 Mar 2004 18:34:44 -0500, Christopher Armstrong 
<radix at twistedmatrix.com> wrote:
>>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 ;-)

> exarkun at divmod.com wrote:
> Actually, it is extremely similar.  It's called a semaphore :) 
> 

To be sure :)

class Semaphore:
     """A semaphore for event driven systems."""

     def __init__(self, tokens):
         self.waiting = []
         self.tokens  = tokens
	self.limit   = tokens

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

         @return Deferred which returns on token acquisition.
         """
	assert self.tokens >= 0
         d = defer.Deferred()
         if not self.tokens:
             self.waiting.append(d)
         else:
             self.tokens = self.tokens - 1
             d.callback(self)
         return d

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

         Should be called by whoever did the acquire() when the shared
         resource is free.
         """
         assert self.tokens < self.limit
         self.tokens = self.tokens + 1
         if self.waiting:
             # someone is waiting to acquire token
             self.tokens = self.tokens - 1
             d = self.waiting.pop(0)
             d.callback(self)

     def _releaseAndReturn(self, r):
         ....

class Lock (Semaphore) :
     def __init__(self) :
         Semaphore.__init__(self, 1)

Andy.




More information about the Twisted-Python mailing list