Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Last active November 18, 2022 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgriffs/ff39d0ed89a0dbaf0d3d3eb6fdc30323 to your computer and use it in GitHub Desktop.
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.
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())
@kgriffs
Copy link
Author

kgriffs commented Nov 18, 2022

Example output:

❯ python async-test.py
async: 202
async: 202
async: 202
async: 202
async: 202
async: 202
async: 202
async: 202
async: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202
sync: 202

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment