Skip to content

Instantly share code, notes, and snippets.

@vxgmichel
Last active November 2, 2016 16:42
Show Gist options
  • Save vxgmichel/9fa643218c60272b3c8f56a0c275305a to your computer and use it in GitHub Desktop.
Save vxgmichel/9fa643218c60272b3c8f56a0c275305a to your computer and use it in GitHub Desktop.
Multitasking example using coroutines
import itertools
import collections
def run(tasks):
# Prepare
results = {}
count = itertools.count()
queue = collections.deque()
for task in tasks:
queue.append((next(count), task))
# Run
while queue:
# Get next task
_, task = queue.popleft()
# Run steps
try:
next(task)
# End of coroutine
except StopIteration as exc:
results[task] = exc.value
# Exception
except Exception as exc:
results[task] = exc
# Schedule next step
else:
queue.append((next(count), task))
# Return results
return [results[task] for task in tasks]
def a():
yield
return 2
def b():
yield
yield
return 3
def x():
ra = yield from a()
rb = yield from b()
return ra + rb
def y():
yield
raise RuntimeError('Oops')
print(run([x(), y()])) # [5, RuntimeError('Oops',)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment