Last active
November 2, 2016 16:42
-
-
Save vxgmichel/9fa643218c60272b3c8f56a0c275305a to your computer and use it in GitHub Desktop.
Multitasking example using coroutines
This file contains hidden or 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
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