Part 13 / Topic 9 of 11
Async I/O in practice
asyncio.to_thread for blocking calls
Many libraries (urllib, sqlite3, reading files) are blocking: they have no await. Calling them directly inside async def freezes the event loop. await asyncio.to_thread(func, arg) runs the function in a worker thread and lets you await the result, so the loop stays free.
Like a waiter who passes a slow job (making fresh juice) to a helper, and keeps serving tables.
import asyncio
from file_server import fetch, start_server, stop_server # run inside examples/
async def main() -> None:
server, base_url = start_server()
names = ["a.txt", "b.txt", "c.txt"]
texts = await asyncio.gather(
*(asyncio.to_thread(fetch, f"{base_url}/files/{n}") for n in names)
)
stop_server(server)
print(texts) # ['contents of a.txt', 'contents of b.txt', 'contents of c.txt']
asyncio.run(main())
fetch() is a normal urllib.request.urlopen call (Part 12). The three downloads take ~0.3 s together instead of ~0.9 s.
Semaphore: limit how many run at once
Starting 1,000 downloads at once can overload a server (and get you blocked). A semaphore is a counter that lets at most N tasks into a block at the same time. The others wait for a free place. Like a lift that takes at most 4 people: everyone gets up, but never more than 4 at once.
import asyncio
active = 0
highest = 0
async def download(name: str, limit: asyncio.Semaphore) -> None:
global active, highest
async with limit: # waits if 2 downloads are already running
active += 1
highest = max(highest, active)
await asyncio.sleep(0.1) # the download
active -= 1
async def main() -> None:
limit = asyncio.Semaphore(2)
await asyncio.gather(*(download(f"file-{n}", limit) for n in range(6)))
print("most at once:", highest) # most at once: 2
asyncio.run(main())
Being polite to servers: limit concurrency (2โ10 is common), add timeouts, and respect 429 Too Many Requests (Part 12).
asyncio.Queue
asyncio.Queue is the async version of queue.Queue (section 3): await queue.get() pauses the task until an item arrives. Workers call queue.task_done() after each item, and await queue.join() waits until every item is done.
import asyncio
async def worker(name: str, jobs: asyncio.Queue) -> None:
while True:
job = await jobs.get()
await asyncio.sleep(0.05)
print(name, "packed", job)
jobs.task_done()
async def main() -> None:
jobs: asyncio.Queue = asyncio.Queue()
for job in ["order-1", "order-2"]:
jobs.put_nowait(job)
task = asyncio.create_task(worker("Kabir", jobs))
await jobs.join() # wait until both jobs are task_done
task.cancel() # the worker loops forever: stop it
asyncio.run(main())
# Kabir packed order-1
# Kabir packed order-2
Full program: examples/07_async_io_practice.py (6 downloads from the local server with Semaphore(2), the server confirms at most 2 at once, then an asyncio.Queue with 2 workers).
๐ Going deeper:
asyncio.to_threaduses a thread pool behind the scenes, so it inherits the same limits as threads. It is perfect for a few blocking calls; for thousands of network calls a real async library is lighter.
Done here? The practice set for Part 13 โ 8 exercises with solutions โ is on the part page.