10/34
Part 4 of 8 · PoolsLearn and do

Run many tables at once, with results in input order

pool.map gives results in input order, and as_completed gives them as they finish

Here are three items that sleep 0.3, 0.1 and 0.2 seconds:

def slow(item):
    name, seconds = item
    time.sleep(seconds)
    return name


items = [("a", 0.3), ("b", 0.1), ("c", 0.2)]

concurrent.futures.ThreadPoolExecutor(max_workers=n) is a thread pool: it runs the calls you hand it on at most n threads of its own. pool.submit(fn, x) returns a future at once. A future is a placeholder for that call's result, and future.result() waits for the call and returns its value.

Four ways to collect the results, with 3 workers:

Predict

Three calls sleep 0.3, 0.1 and 0.2 s on 3 workers. Submitted all at once, about how long does the batch take? And submitted and waited on one at a time?

Pick an answer above to see the rest