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:
| Step | The window, oldest first |
|---|---|
| read r0, r1 and r2, submit each | f0, f1, f2: full |
| hand back f0's result | f1, f2 |
| read r3, submit it | f1, f2, f3: full |
| hand back f1's result | f2, f3 |
| read r4, submit it | f2, 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.