import threading import unittest from collections.abc import Iterable class ThreadSafeCounter: """A counter protected by a lock.""" def __init__(self, initial: int = 0) -> None: self._value = initial self._lock = threading.Lock() @property def value(self) -> int: with self._lock: return self._value def increment(self, amount: int = 1) -> int: with self._lock: self._value += amount return self._value def decrement(self, amount: int = 1) -> int: return self.increment(-amount) class ThreadSafeCounterTests(unittest.TestCase): def test_basic_operations(self) -> None: counter = ThreadSafeCounter(10) self.assertEqual(counter.increment(5), 15) self.assertEqual(counter.decrement(3), 12) self.assertEqual(counter.value, 12) def test_concurrent_increments(self) -> None: counter = ThreadSafeCounter() thread_count = 8 increments_per_thread = 10_000 def increment_many(_: int) -> None: for _ in range(increments_per_thread): counter.increment() threads: Iterable[threading.Thread] = ( threading.Thread(target=increment_many, args=(index,)) for index in range(thread_count) ) threads = list(threads) for thread in threads: thread.start() for thread in threads: thread.join() self.assertEqual(counter.value, thread_count * increments_per_thread) if __name__ == "__main__": unittest.main()