Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 13 / Topic 11 of 11

Putting it together: parallel downloader

The task: download 8 "files" from the local file server (each answer takes 0.3 s) three ways, check that all three got the same contents, and print a timing table.

How it works (examples/08_parallel_downloader.py):

  1. start_server() from file_server.py starts a real http.server on 127.0.0.1 in a daemon thread (port 0 = any free port).
  2. download_sequential() calls fetch() once per URL, one after another.
  3. download_threads() uses ThreadPoolExecutor(max_workers=4) and pool.map, which keeps the URL order.
  4. download_async() uses asyncio.gather + asyncio.to_thread(fetch, url), with a Semaphore(4) so at most 4 requests are in flight.
  5. timed() measures each method with time.perf_counter(); the table shows seconds and the speed-up vs sequential.
  6. The try/finally makes sure the server is stopped even if a download fails.
python 08_parallel_downloader.py

Output (time varies):

8 files, 0.3 s each, 4 at a time

Method               Seconds Speed-up
Sequential              2.42     1.0x
ThreadPoolExecutor      0.61     4.0x
asyncio + to_thread     0.61     3.9x

Same files every way: True
First file says: contents of report-1.csv

8 files with 4 at a time = 2 "rounds" of 0.3 s, so about 0.6 s. Try WORKERS = 8 and see it drop to about 0.3 s.

Done here? The practice set for Part 13 — 8 exercises with solutions — is on the part page.

Search the guide