Python Glossary Русский

Python 3.15+threadingfunction

threading.concurrent_tee()

iterators across threads

Turns one iterator into n independent copies that can be read from different threads: each copy sees the whole sequence.

Syntax

threading.concurrent_tee(iterable, n=2)

This is a thread-safe itertools.tee: the ordinary tee is not designed for its copies to be read from different threads at once. Values are buffered until every copy has read them, so if one copy lags far behind the buffer grows: memory is spent on the gap between the fastest and the slowest reader. Each copy should be read by one thread; if several threads share a copy, wrap it in serialize_iterator as well. n=0 gives an empty tuple, a negative n raises ValueError.

Examples

import threading
left, right = threading.concurrent_tee(iter(range(5)))
results = {}
def read(name, it):
    results[name] = list(it)
threads = [threading.Thread(target=read, args=(n, it)) for n, it in [('L', left), ('R', right)]]
for t in threads: t.start()
for t in threads: t.join()
print(results['L'], results['R'])  # → [0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy