Last active
November 18, 2022 21:22
-
-
Save kgriffs/ff39d0ed89a0dbaf0d3d3eb6fdc30323 to your computer and use it in GitHub Desktop.
Example demonstrating how a synchronous control flow never yields to tasks on the event loop, starving them.
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 httpx | |
import time | |
async def do_work_async(): | |
http = httpx.AsyncClient() | |
while True: | |
resp = await http.get('https://httpbin.org/status/202') | |
print(f'async: {resp.status_code}') | |
await asyncio.sleep(0.5) | |
async def do_work_sync(): | |
http = httpx.Client() | |
while True: | |
resp = http.get('https://httpbin.org/status/202') | |
print(f'sync: {resp.status_code}') | |
time.sleep(0.5) | |
async def main(): | |
t = asyncio.create_task(do_work_async()) | |
await asyncio.sleep(5) | |
await do_work_sync() | |
if __name__ == '__main__': | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: