from __future__ import annotations from threading import Lock, Thread class ThreadSafeCounter: """A counter protected against concurrent access.""" def __init__(self, initial: int = 0) -> None: self._value = initial self._lock = Lock() def increment(self, amount: int = 1) -> int: """Increment the counter and return its new value.""" with self._lock: self._value += amount return self._value def value(self) -> int: """Return a consistent snapshot of the current value.""" with self._lock: return self._value def test_sequential_updates() -> None: counter = ThreadSafeCounter(10) assert counter.increment() == 11 assert counter.increment(4) == 15 assert counter.value() == 15 def test_concurrent_updates() -> None: counter = ThreadSafeCounter() workers = 8 increments_per_worker = 10_000 def increment_repeatedly() -> None: for _ in range(increments_per_worker): counter.increment() threads = [Thread(target=increment_repeatedly) for _ in range(workers)] for thread in threads: thread.start() for thread in threads: thread.join() assert counter.value() == workers * increments_per_worker def main() -> None: test_sequential_updates() test_concurrent_updates() print("All tests passed.") if __name__ == "__main__": main()