Skip to content

Instantly share code, notes, and snippets.

@wilk
Last active May 28, 2018 10:36
Show Gist options
  • Save wilk/2f462b5bf22ace985bd5760dbba5ecf6 to your computer and use it in GitHub Desktop.
Save wilk/2f462b5bf22ace985bd5760dbba5ecf6 to your computer and use it in GitHub Desktop.
Asyncio example: parallel execution
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