Mercurial
comparison asyncio_threads/bank_question/README.md @ 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 ``` | |
| 6 class BankAccount: | |
| 7 def __init__(self, balance): | |
| 8 self.balance = balance | |
| 9 | |
| 10 def deposit(self, amount): | |
| 11 new_balance = self.balance + amount # read | |
| 12 time.sleep(0.1) # simulate delay | |
| 13 self.balance = new_balance # write | |
| 14 | |
| 15 account = BankAccount(0) | |
| 16 | |
| 17 with ThreadPoolExecutor(max_workers=2) as executor: | |
| 18 futures = [ | |
| 19 executor.submit(account.deposit, 500), | |
| 20 executor.submit(account.deposit, 700), | |
| 21 ] | |
| 22 ``` | |
| 23 | |
| 24 Task | |
| 25 | |
| 26 Identify the concurrency bugs in the implementation. | |
| 27 | |
| 28 Explain why these bugs occur. | |
| 29 | |
| 30 Fix the implementation without modifying the existing BankAccount class directly. | |
| 31 | |
| 32 You may use subclassing (Python) or embedding (Go-style composition), depending on the language you choose. | |
| 33 | |
| 34 Ensure your solution is thread-safe and produces the correct final balance (1200). |