Created
August 27, 2022 20:54
-
-
Save EteimZ/a9de53e80d18bb7c83d1230ac94ffe9f to your computer and use it in GitHub Desktop.
snippets on python's coroutines and asyncio library.
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 asyncio | |
| import time | |
| # Hello world async/await | |
| async def hello(): | |
| print("Hello") | |
| await asynio.sleep(2) | |
| print("World!") | |
| asyncio.run(hello()) | |
| # cooperative multitasking using asyncio.gather | |
| async def chill(label: str, n: int): | |
| print(f"{label}: Chilling for {n} seconds") | |
| await asyncio.sleep(n) | |
| print(f"Done chilling for {label}") | |
| async def gather(): | |
| T = asyncio.gather(chill("A", 2), chill("B", 5), chill("C", 3)) | |
| starttime = time.perf_counter() | |
| await T | |
| endtime = time.perf_counter() | |
| print(f"Task finished in {endtime - starttime}") | |
| asyncio.run(gather()) | |
| """ Sample output: | |
| A: Chilling for 2 seconds | |
| B: Chilling for 5 seconds | |
| C: Chilling for 3 seconds | |
| Done chilling for A | |
| Done chilling for C | |
| Done chilling for B | |
| Task finished in 5.004022927998449 | |
| """ | |
| async def task_create(): | |
| task1 = asyncio.create_task(chill("A", 2)) | |
| task2 = asyncio.create_task(chill("B", 5)) | |
| task3 = asyncio.create_task(chill("C", 3)) | |
| starttime = time.perf_counter() | |
| await task1 | |
| await task2 | |
| await task3 | |
| endtime = time.perf_counter() | |
| print(f"Task finished in {endtime - starttime}") | |
| asyncio.run(task_create()) | |
| """ Sample Output: | |
| A: Chilling for 2 seconds | |
| B: Chilling for 5 seconds | |
| C: Chilling for 3 seconds | |
| Done chilling for A | |
| Done chilling for C | |
| Done chilling for B | |
| Task finished in 5.003572109999368 | |
| """ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment