CLI journal project (4/6): asyncio and batch reads

Use gather, a semaphore, and run_in_executor so disk reads of several logs do not block the event loop. Twelve exercises, plus a sync fallback.

Illustration : faisceaux lumineux parallèles transportant de petites tâches vers un ordinateur portable, image du traitement asynchrone par lots

AI-generated illustration

Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.

When you analyze several large files, you can run the work in parallel: asyncio.gather starts tasks that wait on I/O. Careful: reading a file with synchronous open() blocks the loop. A common pattern is await loop.run_in_executor(None, parse_file_sync, path), where parse_file_sync reads and aggregates in a thread (disk I/O often releases the GIL).

A minimal alternative is to stay fully synchronous with concurrent.futures.ThreadPoolExecutor for this project — but document the choice: the advanced course asks you to illustrate asyncio.

Previous chapter: decorators and metrics.

async def process_paths(paths: list[Path]) -> Report:
    loop = asyncio.get_running_loop()
    sem = asyncio.Semaphore(4)

    async def one(p: Path):
        async with sem:
            return await loop.run_in_executor(None, parse_and_count, p)

    parts = await asyncio.gather(*[one(p) for p in paths])
    return merge_reports(parts)

Exercises (12)

Exercise 1 — Write asyncio.run plus a main() coroutine that await asyncio.sleep(0). Easy

Show the solution
import asyncio
async def main():
    await asyncio.sleep(0)
asyncio.run(main())

Exercise 2 — Limit concurrency to 4 files with Semaphore(4). Intermediate

Show the solution
sem = asyncio.Semaphore(4)
async with sem:
    ...

Exercise 3 — Why run_in_executor for open / reading? Intermediate

Show the solution
# Avoid blocking the event loop on synchronous I/O.

Exercise 4 — Merge two Counter objects with sum or counter.update. Easy

Show the solution
from collections import Counter
a = Counter({"INFO": 1})
a.update(Counter({"INFO": 2, "ERROR": 1}))

Exercise 5 — gather with return_exceptions=True: the case of a missing file. Hard

Show the solution
# Collect FileNotFoundError in the list for an error report.

Exercise 6 — asyncio.run must not be called inside a coroutine — why? Intermediate

Show the solution
# Nested loops are not allowed; await coroutines instead.

Exercise 7 — Benchmark: sync versus async plus executor on 10 files — when is the gain zero? Hard

Show the solution
On a slow disk or with tiny files; scheduling overhead.

Exercise 8 — aiofiles (third party) — when should you add it? Intermediate

Show the solution
Native async read and write without a thread pool; a pip dependency.

Exercise 9 — uvloop — the context (Linux/macOS). Hard

Show the solution
A faster alternative event loop; optional.

Exercise 10 — asyncio.to_thread (3.9+) — equivalent to run_in_executor. Intermediate

Show the solution
await asyncio.to_thread(parse_and_count, path)

Exercise 11 — A synchronous main calls asyncio.run once — a single entry point. Easy

Show the solution
def main():
    return asyncio.run(amain())

Exercise 12 — Document the fallback: if --no-async, process files sequentially and synchronously. Hard

Show the solution
Works in restricted environments; simpler to debug.

Next

Typing and mypy

Amazon

Check today’s price on Amazon

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.