Python Glossary Русский

Python 3.15+threadingterm

threading.serialize_iterator()

iterators across threads

A wrapper that lets several threads safely take items from one iterator or generator: each item goes to exactly one thread.

Syntax

threading.serialize_iterator(iterable)

A generator cannot be advanced from two threads at once: a second next() while the first is running raises ValueError: generator already executing, and pure-Python iterators may corrupt their state. serialize_iterator puts a lock around next() (and around send, throw and close if they exist): threads receive items one at a time, with no duplicates or gaps. Values are not buffered, so a thread arriving during someone else's next() waits. This distributes work rather than copying it: if every thread needs the whole sequence, use threading.concurrent_tee.

Examples

import threading
def numbers():
    yield from range(100)
source = threading.serialize_iterator(numbers())
taken = []
def worker():
    for n in source:
        taken.append(n)
threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(len(taken), sorted(taken) == list(range(100)))  # → 100 True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy