Fixing a Lost-Update Race in a Deposit Method You Cannot Edit
Data Structure DesignModel answerLast updated
Diagnose the race in an account deposit that reads, pauses, then writes, and add locking through a subclass, wrapper or embedding in Python and Go without touching the original type.
You are given an account class that several threads share. Its deposit method reads the balance into a local variable, pauses to simulate processing, and then writes back the local value plus the amount.
import time
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
current = self.balance # read
time.sleep(0.1) # simulated processing delay
self.balance = current + amount # write
Multiple threads in one process call deposit on the same object at the same time. Diagnose the problem, fix it, and then repeat the fix in Go.
Rules
BankAccountmust not be modified. Pasting its body into a new class and editing that copy is not allowed. The safe version has to call the existingdepositthrough a subclass or a wrapper.- Treat the
time.sleep(0.1)as part of the method you cannot change. It stands in for real work between the read and the write. - All threads live in one process and share one account object.
Part 1: Find the bugs. List every concurrency defect in deposit and name the root cause. Walk through a concrete two-thread run starting at balance 0 that ends with a wrong balance, giving the expected and actual results. Say whether removing the delay would make the method correct.
Part 2: Fix it in Python. Write the thread-safe version under the rules above. Show where the lock lives, when it is created, and which statements it protects. Explain how callers should read the balance and how you would write a test that fails reliably before the fix and passes after it.
Part 3: Fix it in Go. Here is the same account in Go:
type BankAccount struct {
Balance int
}
func (a *BankAccount) Deposit(amount int) {
current := a.Balance
time.Sleep(100 * time.Millisecond)
a.Balance = current + amount
}
Go has no inheritance. Build a thread-safe equivalent without editing BankAccount, and explain what can still go wrong silently.
State any assumptions you make, for example whether other methods must be safe, whether one lock per account is expected, and whether anything beyond threads in one process is involved.
Hints
Hint 1
Ask what the method does as a sequence of steps: a read, some work, then a write that depends on the earlier read. What happens if another thread runs between those steps?
Hint 2
The lock must be held across the whole read-delay-write sequence, so wrap the call to the inherited method instead of locking inside separate pieces. Create one lock per account in the constructor, not per call and not at module level by accident.
Hint 3
In Go, embed the original struct in a new struct together with a sync.Mutex, and define a Deposit on the wrapper that locks, defers the unlock, and calls the embedded method. Think about pointer versus value receivers, copying a mutex, and callers who can still reach the inner struct directly.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: What is wrong
Root cause: a non-atomic read-modify-write on shared state. deposit reads self.balance, computes from the stale copy, and writes the result. Nothing prevents another thread from doing the same in between, so one update overwrites the other. This is a lost update.
The delay is only an amplifier. The sleep widens the window between read and write, which makes the failure almost certain. It does not cause it.
Concrete run, starting balance 0, two threads each depositing 100:
- Thread A reads
balanceintocurrent(0). - Thread B reads
balanceintocurrent(0). - A writes
0 + 100 = 100. - B writes
0 + 100 = 100.
Expected final balance: 200. Actual: 100. With N threads that all start together, the result is often just one deposit's worth.
Would removing the sleep fix it? No. In CPython, self.balance = current + amount involves several bytecode steps, and a thread switch can occur between the load and the store. The GIL guarantees memory safety of the interpreter, not atomicity of your logic. The race would be rare and therefore far more dangerous, since it would pass tests and fail in production. In Go it is a genuine data race, which is undefined-ish behavior under the memory model, not just a logic error.
Part 2: Python fix
Use a subclass that owns a lock and calls the original method under it.
import threading
class SafeBankAccount(BankAccount):
def __init__(self, balance=0):
super().__init__(balance)
self._lock = threading.Lock() # one lock per account, created at construction
def deposit(self, amount):
with self._lock: # covers read, delay and write
super().deposit(amount)
def get_balance(self):
with self._lock:
return self.balance
Key points:
- Reuse, not copy.
super().depositruns the original code unchanged. - Lock ownership. The lock is created in
__init__, so it is per instance. A module-level lock would also be correct but would serialize unrelated accounts needlessly. - Critical section. It must cover the entire call, because the invariant spans read to write. Locking only the write, or only the read, does nothing useful.
- Reads. A plain read of an int is atomic in CPython, but it can observe the balance mid-update from the caller's view (for example between two related deposits). A locked getter gives a consistent view and does not depend on interpreter details.
- Wrapper alternative. If subclassing is awkward (the object is created elsewhere), wrap an existing instance: hold
self._accountand a lock, and delegatedeposit. Either approach is acceptable; the wrapper needs the caller to stop using the raw object. - Trade-off. Holding a lock across a 100 ms call serializes deposits, so 10 threads take about 1 second instead of 100 ms. That is unavoidable here because the sleep is inside the method we cannot change. Use
Lock, notRLock, unlessdepositcould call itself or another locked method on the same thread (re-entrancy), in which caseLockwould deadlock. - Not covered. This protects threads in one process. Several processes or hosts need a database transaction, an atomic increment, or a distributed lock.
Test that fails reliably before the fix. The sleep makes the race deterministic enough:
def run(account, n=10, amount=10):
threads = [threading.Thread(target=account.deposit, args=(amount,)) for _ in range(n)]
for t in threads: t.start()
for t in threads: t.join()
return account.balance
assert run(BankAccount()) != 100 # almost always 10 or a few deposits' worth
assert run(SafeBankAccount()) == 100
For a stricter test, use a threading.Barrier so all threads start together, and assert the balance equals n * amount. Negative testing against the unsafe class shows the test has teeth.
Part 3: Go version
Go uses composition. Embed the original struct and add a mutex.
type SafeAccount struct {
mu sync.Mutex
BankAccount
}
func (a *SafeAccount) Deposit(amount int) {
a.mu.Lock()
defer a.mu.Unlock()
a.BankAccount.Deposit(amount)
}
func (a *SafeAccount) Balance() int {
a.mu.Lock()
defer a.mu.Unlock()
return a.BankAccount.Balance
}
Details:
- Method resolution.
SafeAccountdefines its ownDeposit, which shadows the promoted one. Inside, the explicita.BankAccount.Depositcalls the original. This is shadowing, not overriding: there is no dynamic dispatch. - Pointer receivers. Use
*SafeAccountso the lock and the data are shared. A value receiver would copy the mutex and lock a private copy, protecting nothing. - Never copy a mutex after first use. Pass
*SafeAccount, and letgo vet(copylocks) flag mistakes. - Unlock on all paths.
deferhandles early returns and panics.
What can still go wrong silently:
- Bypass through the embedded field.
acct.BankAccount.Deposit(5)oracct.Balance(the field, promoted) skips the lock. Fix by embedding as an unexported field (acct *BankAccount) so callers can only use the safe methods. Note that an exported getter namedBalanceconflicts with the promoted field name, which is another reason to hide the inner struct. - Interface confusion. If code accepts an interface satisfied by
*BankAccount, someone may pass the inner value and lose the protection. - Value copies of
SafeAccount, as noted above. - Missed detection. Run tests with
go test -race; the race detector flags the unsynchronized version immediately. - Lock held across slow work serializes callers, as in Python.
sync.Mutexis not re-entrant, so callingDepositfrom inside a locked method deadlocks.
Common mistakes
- Locking only the assignment, or creating a new lock inside each
depositcall. - Removing the sleep and declaring victory.
- Copying the class body, which violates the rules.
- Forgetting that readers need synchronization too.