Thread‑safe iterator implementation

Protect the exhaustion check, item retrieval and cursor increment with one lock. Copy the input to a tuple so external changes to the original sequence cannot invalidate the iterator's indexing.

Короткий ответ

Что ответить на собеседовании

Protect the exhaustion check, item retrieval and cursor increment with one lock. Copy the input to a tuple so external changes to the original sequence cannot invalidate the iterator's indexing.

Подробный разбор

Ответ с пояснениями

Условие

Реализуйте класс, соответствующий протоколу итератора Python, и обеспечивающий безопасную работу при использовании одновременно из нескольких потоков. Итератор должен правильно обрабатывать параллельные обращения, сохраняя целостность внутреннего состояния во время итерации.

import threading

class Iterable:
    def __init__(self, data):
        self.data = data
        self.cursor = 0
        # TODO: добавить потокобезопасность

    def __iter__(self):
        return self

    def __next__(self):
        # TODO: потокобезопасный доступ к self.cursor и self.data
        pass

Ответ

Protect the exhaustion check, item retrieval and cursor increment with one lock. Copy the input to a tuple so external changes to the original sequence cannot invalidate the iterator's indexing.

A single shared iterator distributes each position to at most one caller:

import threading

class Iterable:
    def __init__(self, data):
        self.data = tuple(data)
        self.cursor = 0
        self.lock = threading.Lock()

    def __iter__(self):
        return self

    def __next__(self):
        with self.lock:
            if self.cursor >= len(self.data):
                raise StopIteration
            value = self.data[self.cursor]
            self.cursor += 1
            return value

Do not mutate the input concurrently while constructing the snapshot. The lock protects iteration, not mutable objects stored inside the tuple. Assignment order is serialized, but processing or printing returned values across threads may occur in a different order.

ИИ-помощник для собеседований

Хочешь уверенно проходить собеседования?

Попробуй ИИ-помощник для собеседований: слышит вас и собеседника, анализирует экран, подсказывает ответы в реальном времени, работает без VPN и не попадает в захват экрана.

Подробнее