Skip to content

Instantly share code, notes, and snippets.

@bobpoekert
Created April 18, 2012 22:09
Show Gist options
  • Select an option

  • Save bobpoekert/2416967 to your computer and use it in GitHub Desktop.

Select an option

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
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()
@bobpoekert

Copy link
Copy Markdown
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment