Created
February 9, 2021 13:06
-
-
Save jorenham/58ccab323710cef2f096aa6f9b968444 to your computer and use it in GitHub Desktop.
demonstration of why asyncio.shield is misleading
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 | |
async def task(): | |
print('task start') | |
await asyncio.sleep(.5) | |
print('task done') | |
async def run_tasks(): | |
while True: | |
await asyncio.shield(task()) | |
async def main(): | |
loop = asyncio.get_running_loop() | |
task_runner = loop.create_task(run_tasks()) | |
await asyncio.sleep(.75) | |
task_runner.cancel() | |
await task_runner | |
# expectation: 'task done' is always printed because of asyncio.shield | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment