Concurrent bank account debugging (thread safety)
You are given a simple BankAccount object that is used concurrently from multiple threads. Two deposits run at the same time:
account = BankAccount(0)
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [
executor.submit(account.deposit, 500),
executor.submit(account.deposit, 700),
]
A simplified implementation of deposit() looks like this:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
new_balance = self.balance + amount # Read
time.sleep(0.1) # Delay
self.balance = new_balance # Write
Tasks
-
Explain why this code can produce an incorrect final balance (e.g.,
700
instead of the expected
1200
).
-
Identify the underlying concurrency bug(s).
-
Propose and describe a correct fix that ensures thread safety for
deposit()
.
-
Mention any important caveats or alternatives (e.g., performance trade-offs, other synchronization approaches).