Created
April 18, 2012 22:09
-
-
Save bobpoekert/2416967 to your computer and use it in GitHub Desktop.
Multi: A helper class for waiting on multiple asynchronous things happening in parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Multi(object): | |
def __init__(self, callback): | |
self.callback = callback | |
self.counter = 0 | |
self.fired = False | |
self.started = False | |
def enter(self): | |
assert not self.started | |
self.counter += 1 | |
def exit(self): | |
self.counter -= 1 | |
if self.counter == 0 and self.started and not self.fired: | |
self.callback() | |
self.fired = True | |
def start(self): | |
self.started = True | |
if self.counter <= 0: | |
self.callback() | |
self.fired = True | |
if __name__ == '__main__': | |
def c(): | |
print 'done' | |
m = Multi(c) | |
for i in xrange(20): | |
m.enter() | |
m.start() | |
for i in xrange(20): | |
m.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a class I end up defining on every async project I work on. It's the cleanest way I know of to have a callback fire when a set of operations finish, regardless of the order that the operations happen in. It really should be in functools.