Language: Python
python
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return True
return False
# Two threads calling withdraw(100) at nearly the same time
# on an account with balance = 100
What breaks here under concurrent access? 👇
.
.
.
The bug: Classic check-then-act race condition (a cousin of the counter bug from Spot the Bug #2, but with real money on the line). Thread A checks
100 <= 100 → true. Before it subtracts, Thread B also checks 100 <= 100 → true. Now BOTH threads proceed to withdraw, and the balance goes to -100 - the check and the action weren't atomic together.Fixed version (using a lock):
python
import threading
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def withdraw(self, amount):
with self.lock:
if amount <= self.balance:
self.balance -= amount
return True
return False
The lock ensures the check-and-subtract happens as one atomic unit - no other thread can interleave in the middle.
💡 This exact pattern (check-then-act on shared state) is one of the most common sources of real financial bugs in production systems, not just interview trivia. Any time you see "if condition, then modify shared state," ask: "can two threads see the same 'before' state at once?"
Have you seen a check-then-act bug in real code before? 👇