[Twisted-Python] Lock class using Deferreds

Christopher Armstrong radix at twistedmatrix.com
Sat Mar 6 00:00:12 MST 2004


Andy Gayton wrote:
>> 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."""

My thing looks somewhat different; there's no 'release'...

I haven't really put much time into figuring out what's going on in this 
thread, but exarkun wanted me to post my code. It's got a couple of 
things in it that are app-specific and probably isn't optimally factored.


class DeferredQueue:

     MAX_REQUESTS = 20

     def __init__(self, source, request):
         self.deferreds = {}
         self.source = source
         self.request = request
         for _ in range(self.MAX_REQUESTS):
             self.getMore()

     def getMore(self):
         assert len(self.deferreds) < self.MAX_REQUESTS

         try:
             sink, input = self.source.next()
         except StopIteration:
             return

         d = self.request(input)
         self.deferreds[input] = d

         #XXX fixme app-specific
         d.addBoth(self._cbGotSync, input)
         d.addCallback(sink)

         def _err(f):
             #XXX fixme app-specific
             if f.check(NotSync, defer.TimeoutError):
                 return
             print f
             return

         d.addErrback(_err)

     def _cbGotSync(self, result, input):
         del self.deferreds[input]
         self.getMore()
         return result



-- 
  Twisted | Christopher Armstrong: International Man of Twistery
   Radix  |          Release Manager,  Twisted Project
---------+           http://radix.twistedmatrix.com/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 256 bytes
Desc: OpenPGP digital signature
URL: </pipermail/twisted-python/attachments/20040306/145e5a8e/attachment.sig>


More information about the Twisted-Python mailing list