diff asyncio_threads/bank_question/main.py @ 48:46daba6e3cf4

Few python scrtips to show how to use asychio.
author MrJuneJune <me@mrjunejune.com>
date Sat, 13 Dec 2025 14:23:02 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/asyncio_threads/bank_question/main.py	Sat Dec 13 14:23:02 2025 -0800
@@ -0,0 +1,43 @@
+# # Bank Account
+# 
+# You are given a simplified multi-threaded “bank account” implementation used by one of our infrastructure teams. The current code processes deposits concurrently but produces incorrect results.
+# 
+# Task
+# 
+# Identify the concurrency bugs in the implementation.
+# 
+# Explain why these bugs occur.
+# 
+# Fix the implementation without modifying the existing BankAccount class directly.
+# 
+# You may use subclassing (Python) or embedding (Go-style composition), depending on the language you choose.
+# 
+# Ensure your solution is thread-safe and produces the correct final balance (1200).
+
+from threading import Lock
+from concurrent.futures import ThreadPoolExecutor
+import time
+
+class BankAccount:
+    def __init__(self, balance):
+        self.balance = balance
+        self._lock = Lock()
+
+    def deposit(self, amount):
+        while (self._lock.locked()):
+            pass
+        self._lock.acquire()
+        new_balance = self.balance + amount  # read
+        time.sleep(0.1)                      # simulate delay
+        self.balance = new_balance           # write
+        self._lock.release()
+
+
+account = BankAccount(0)
+
+with ThreadPoolExecutor(max_workers=2) as executor:
+    futures = [
+        executor.submit(account.deposit, 500),
+        executor.submit(account.deposit, 700),
+    ]
+print(account.balance)