Forked from yeraydiazdiaz/1b-cooperatively-scheduled-asyncio-await.py
Last active
September 15, 2017 04:12
-
-
Save ketanarlulkar/1117ff0f41fad9e51aeff4129cf41a29 to your computer and use it in GitHub Desktop.
Understanding use of AsyncIO Library in Python
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 time | |
import asyncio | |
start = time.time() | |
def tic(): | |
return 'at %1.1f seconds' % (time.time() - start) | |
async def gr1(): | |
# Busy waits for a second, but we don't want to stick around... | |
print('gr1 started work: {}'.format(tic())) | |
await asyncio.sleep(5) | |
print('gr1 ended work: {}'.format(tic())) | |
async def gr2(): | |
# Busy waits for a second, but we don't want to stick around... | |
print('gr2 started work: {}'.format(tic())) | |
await asyncio.sleep(2) | |
print('gr2 Ended work: {}'.format(tic())) | |
async def gr3(): | |
print("Let's do some stuff while the coroutines are blocked, {}".format(tic())) | |
await asyncio.sleep(3) | |
print("Done @ {}".format(tic())) | |
io_loop = asyncio.get_event_loop() | |
tasks = [ | |
io_loop.create_task(gr1()), | |
io_loop.create_task(gr2()), | |
io_loop.create_task(gr3()) | |
] | |
io_loop.run_until_complete(asyncio.wait(tasks)) | |
io_loop.close() |
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
gr1 started work: at 0.0 seconds | |
gr2 started work: at 0.0 seconds | |
Let's do some stuff while the coroutines are blocked, at 0.0 seconds | |
gr2 Ended work: at 2.0 seconds | |
Done @ at 3.0 seconds | |
gr1 ended work: at 5.0 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment