Skip to content

Instantly share code, notes, and snippets.

@walkingpendulum
Created August 3, 2017 09:49
Show Gist options
  • Save walkingpendulum/68057e12ef14028d5fa681075c658760 to your computer and use it in GitHub Desktop.
Save walkingpendulum/68057e12ef14028d5fa681075c658760 to your computer and use it in GitHub Desktop.
asyncio tutorial
"""
$ python3 main.py
Compute 1 + 10 ...
Compute 10 - 1 ...
10 - 1 = 9
1 + 10 = 11
"""
import asyncio
async def compute(x, y, f, desc, t_sec):
print(desc % (x, y))
await asyncio.sleep(t_sec)
return f(x, y)
async def print_sum(x, y):
result = await compute(x, y, lambda x, y: x + y, "Compute %s + %s ...", 1.0)
print("%s + %s = %s" % (x, y, result))
async def print_sub(x, y):
result = await compute(x, y, lambda x, y: x - y, "Compute %s - %s ...", 0.4)
print("%s - %s = %s" % (x, y, result))
async def main(loop):
sum_task = loop.create_task(print_sum(1, 10))
sub_task = loop.create_task(print_sub(10, 1))
await sub_task
await sum_task
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment