27/34
Part 8 of 8 · Follow-upsLearn and do

A million tables: pool.map reads every item first, so keep a window of futures

In Python 3.12, pool.map reads its whole input before it hands back the first result: the docs say it collects the iterables immediately, not lazily. Fed a generator of 200 records of 20 KB each, pool.map on 4 threads pulled all 200 before the first result came back. Memory peaked at 4.41 MB, by tracemalloc. With a million records, that's every record in memory at once, plus a future for each.

Keep a window of futures instead. It submits until limit calls are pending, then hands back the oldest result before it reads the next record. Here is the window with limit = 3, oldest future on the left:

StepThe window, oldest first
read r0, r1 and r2, submit eachf0, f1, f2: full
hand back f0's resultf1, f2
read r3, submit itf1, f2, f3: full
hand back f1's resultf2, f3
read r4, submit itf2, f3, f4

The results stay in input order, and at most limit records are held. The measurement, with a counter in the generator:

pulled = 0


def records(n, size):
    global pulled
    for i in range(n):
        pulled += 1
        yield bytes([i % 256]) * size


def work(record):
    time.sleep(0.002)
    return len(record)


with ThreadPoolExecutor(max_workers=4) as pool:
    # or pool.map(work, records(200, 20_000))
    results = bounded_map(pool, work, records(200, 20_000), 8)
    first = next(results)
    print(pulled)

pool.map printed 200, and bounded_map with limit=8 printed 8. Memory peaked at 0.19 MB against 4.41 MB, and both runs took 0.152 s in all.

Python 3.14 builds this into Executor.map: a new buffersize argument limits how many submitted calls can wait with results not yet handed back. The other classic shape is a reader thread that feeds workers through queue.Queue(maxsize=n). A put into a full queue blocks until a worker takes an item out. Either way, a slow consumer slows the reader down instead of letting memory grow.

In the editor, write the generator bounded_map(pool, fn, items, limit), with the window of futures in a deque.