import threading import unittest from concurrent.futures import ThreadPoolExecutor class ThreadSafeCounter: """A counter protected against concurrent access.""" 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 @property def value(self) -> int: """Return the current counter value.""" with self._lock: return self._value class ThreadSafeCounterTests(unittest.TestCase): def test_increment(self) -> None: counter = ThreadSafeCounter(10) self.assertEqual(counter.increment(), 11) self.assertEqual(counter.increment(4), 15) self.assertEqual(counter.value, 15) def test_concurrent_increments(self) -> None: counter = ThreadSafeCounter() increments = 10_000 # Multiple workers update the same counter concurrently. with ThreadPoolExecutor(max_workers=8) as executor: list(executor.map(lambda _: counter.increment(), range(increments))) self.assertEqual(counter.value, increments) if __name__ == "__main__": unittest.main()