[Twisted-Python] Limiting number of concurrent client connections

Justin Johnson justinjohnson at gmail.com
Tue Jun 28 09:53:45 EDT 2005

This isn't the best solution, but I've been using a semaphore to limit the 
number of "tasks" that take place at a time. I've also been doing some 
research on IOCP and plan on adding some missing functionality to the IOCP 
reactor so I don't have to use the win32eventreactor anymore.
from twisted.internet import defer

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.tokens = self.tokens - 1
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)

def _releaseAndReturn(self, r):
return r

def run(self, f, *args, **kwargs):
"""Acquire token, run function, release token.

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

 On 6/28/05, Toby Dickenson <tdickenson at devmail.geminidataloggers.co.uk> 
> Im finding that Win32Reactor raises an exception on every iteration of the
> main loop if I exceed the limit of 64 WaitForMultipleObjects.
> I would prefer to avoid this fairly obvious denial-of-service problem by
> limiting the number of concurrent client connections. Is there a standard
> solution for this?
> Thanks in advance,
> --
> Toby Dickenson
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20050628/1cb432ae/attachment.htm 

More information about the Twisted-Python mailing list