Last active
May 28, 2018 10:36
-
-
Save wilk/2f462b5bf22ace985bd5760dbba5ecf6 to your computer and use it in GitHub Desktop.
Asyncio example: parallel execution
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
import asyncio | |
from time import sleep | |
from concurrent.futures import ThreadPoolExecutor | |
async def hello_world(loop, delay): | |
print("hello world") | |
await loop.run_in_executor(ThreadPoolExecutor(), sleep, delay) | |
print("hello there") | |
return "done" | |
loop = asyncio.get_event_loop() | |
try: | |
coroutines = [ | |
hello_world(loop, 1), | |
hello_world(loop, 2) | |
] | |
tasks, _ = loop.run_until_complete(asyncio.wait(coroutines)) | |
results = list(map(lambda t: t.result(), tasks)) | |
print(results) | |
except Exception: | |
# error handling | |
pass | |
finally: | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment