from __future__ import annotations from threading import Lock, Thread from typing import Callable class ThreadSafeCounter: """A counter protected against concurrent access.""" def __init__(self, initial: int = 0) -> None: self._value = initial self._lock = Lock() @property def value(self) -> int: with self._lock: return self._value def increment(self, amount: int = 1) -> int: """Atomically increment the counter and return its new value.""" with self._lock: self._value += amount return self._value def reset(self) -> None: with self._lock: self._value = 0 def test_basic_operations() -> None: counter = ThreadSafeCounter(2) assert counter.increment() == 3 assert counter.increment(4) == 7 counter.reset() assert counter.value == 0 def test_concurrent_increments() -> None: counter = ThreadSafeCounter() increments_per_thread = 10_000 def worker() -> None: for _ in range(increments_per_thread): counter.increment() threads = [Thread(target=worker) for _ in range(8)] for thread in threads: thread.start() for thread in threads: thread.join() assert counter.value == len(threads) * increments_per_thread def main() -> None: tests: tuple[Callable[[], None], ...] = ( test_basic_operations, test_concurrent_increments, ) for test in tests: test() print("All tests passed.") if __name__ == "__main__": main()