|
| 1 | +import threading |
| 2 | +import time |
| 3 | +from concurrent.futures import ThreadPoolExecutor |
| 4 | + |
| 5 | +bank_open = threading.Event() |
| 6 | +transactions_open = threading.Event() |
| 7 | + |
| 8 | + |
| 9 | +def serve_customer(customer_data): |
| 10 | + print(f"{customer_data['name']} is waiting for the bank to open.") |
| 11 | + |
| 12 | + bank_open.wait() |
| 13 | + print(f"{customer_data['name']} entered the bank") |
| 14 | + if customer_data["type"] == "WITHDRAW_MONEY": |
| 15 | + print(f"{customer_data['name']} is waiting for transactions to open.") |
| 16 | + transactions_open.wait() |
| 17 | + print(f"{customer_data['name']} is starting their transaction.") |
| 18 | + |
| 19 | + # Simulate the time taken for performing the transaction |
| 20 | + time.sleep(2) |
| 21 | + |
| 22 | + print(f"{customer_data['name']} completed transaction and exited bank") |
| 23 | + else: |
| 24 | + # Simulate the time taken for banking |
| 25 | + time.sleep(2) |
| 26 | + print(f"{customer_data['name']} has exited bank") |
| 27 | + |
| 28 | + |
| 29 | +customers = [ |
| 30 | + {"name": "Customer 1", "type": "WITHDRAW_MONEY"}, |
| 31 | + {"name": "Customer 2", "type": "CHECK_BALANCE"}, |
| 32 | + {"name": "Customer 3", "type": "WITHDRAW_MONEY"}, |
| 33 | + {"name": "Customer 4", "type": "WITHDRAW_MONEY"}, |
| 34 | +] |
| 35 | + |
| 36 | +with ThreadPoolExecutor(max_workers=4) as executor: |
| 37 | + for customer_data in customers: |
| 38 | + executor.submit(serve_customer, customer_data) |
| 39 | + |
| 40 | + print("Bank manager is preparing to open the bank.") |
| 41 | + time.sleep(2) |
| 42 | + print("Bank is now open!") |
| 43 | + bank_open.set() # Signal that the bank is open |
| 44 | + |
| 45 | + time.sleep(3) |
| 46 | + print("Transactions are now open!") |
| 47 | + transactions_open.set() |
| 48 | + |
| 49 | + |
| 50 | +print("All customers have completed their transactions.") |
0 commit comments