import threading from concurrent.futures import ThreadPoolExecutor class ThreadSafeCounter: """A counter whose operations are safe across threads.""" def __init__(self, initial: int = 0) -> None: self._value = initial self._lock = threading.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 counter.""" with self._lock: return self._value def test_basic_operations() -> None: counter = ThreadSafeCounter(10) assert counter.value() == 10 assert counter.increment() == 11 assert counter.increment(4) == 15 def test_concurrent_increments() -> None: counter = ThreadSafeCounter() workers = 8 increments_per_worker = 1_000 def increment_repeatedly() -> None: for _ in range(increments_per_worker): counter.increment() # Exercise the counter concurrently. with ThreadPoolExecutor(max_workers=workers) as executor: futures = [executor.submit(increment_repeatedly) for _ in range(workers)] for future in futures: future.result() assert counter.value() == workers * increments_per_worker def main() -> None: test_basic_operations() test_concurrent_increments() print("All tests passed.") if __name__ == "__main__": main()