Python Glossary Русский

Python 3.2+concurrent.futuresfunction

concurrent.futures.as_completed()

task pool

Returns an iterator that yields the Futures as they finish — in the order they become ready, not the order they were created.

Syntax

from concurrent.futures import as_completed
for future in as_completed(fs): ...

The iterator yields Future objects, not results, and the original order is gone — the usual trick is a dict mapping each future back to its input. Reach for as_completed when you want to handle answers the moment they arrive; if you need results in the order of the inputs, executor.map() is simpler. The optional timeout is measured from the as_completed call itself, not per future.

Examples

from concurrent.futures import ThreadPoolExecutor, as_completed
import time, random
def task(n):
    time.sleep(random.random())
    return n * 2
with ThreadPoolExecutor() as ex:
    futures = [ex.submit(task, i) for i in range(5)]
    for f in as_completed(futures):
        print(f.result())  # выводит по мере готовности

See also

Open in the full glossarydocs.python.orgReport an inaccuracy