Mercurial
comparison 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 |
comparison
equal
deleted
inserted
replaced
| 47:829623189a57 | 48:46daba6e3cf4 |
|---|---|
| 1 # # Bank Account | |
| 2 # | |
| 3 # 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. | |
| 4 # | |
| 5 # Task | |
| 6 # | |
| 7 # Identify the concurrency bugs in the implementation. | |
| 8 # | |
| 9 # Explain why these bugs occur. | |
| 10 # | |
| 11 # Fix the implementation without modifying the existing BankAccount class directly. | |
| 12 # | |
| 13 # You may use subclassing (Python) or embedding (Go-style composition), depending on the language you choose. | |
| 14 # | |
| 15 # Ensure your solution is thread-safe and produces the correct final balance (1200). | |
| 16 | |
| 17 from threading import Lock | |
| 18 from concurrent.futures import ThreadPoolExecutor | |
| 19 import time | |
| 20 | |
| 21 class BankAccount: | |
| 22 def __init__(self, balance): | |
| 23 self.balance = balance | |
| 24 self._lock = Lock() | |
| 25 | |
| 26 def deposit(self, amount): | |
| 27 while (self._lock.locked()): | |
| 28 pass | |
| 29 self._lock.acquire() | |
| 30 new_balance = self.balance + amount # read | |
| 31 time.sleep(0.1) # simulate delay | |
| 32 self.balance = new_balance # write | |
| 33 self._lock.release() | |
| 34 | |
| 35 | |
| 36 account = BankAccount(0) | |
| 37 | |
| 38 with ThreadPoolExecutor(max_workers=2) as executor: | |
| 39 futures = [ | |
| 40 executor.submit(account.deposit, 500), | |
| 41 executor.submit(account.deposit, 700), | |
| 42 ] | |
| 43 print(account.balance) |