Middle
Debugging task: fix race condition during money withdrawal (two parallel requests may withdraw more than available on the account)
sobes.tech AI
Answer from AI
A race condition during money withdrawal occurs when two parallel requests check the balance and withdraw money simultaneously, without seeing each other's changes, which can lead to withdrawing more than is available in the account.
To fix this in Python, you need to ensure the atomicity of the withdrawal operation. One way is to use a lock so that only one thread can perform the check and withdrawal at the same time.
Example using threading.Lock:
import threading
class Account:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def withdraw(self, amount):
with self.lock: # lock access for other threads
if self.balance >= amount:
self.balance -= amount
return True
else:
return False
account = Account(100)
# Calls to account.withdraw(amount) from different threads will be safe
If a database is used, it is better to apply transactions with locks or atomic operations at the database level to avoid race conditions.