Given code for a banking application where multiple threads execute different functions in parallel, explain the code, identify bugs and suggest fixes/optimizations for multithreaded execution (e.g. locks, read-write lock, concurrent hash map). Asked in the Debugging round stage.
Implement the corrected transfer logic. Each transfer is [source, destination, amount]. Execute transfers in parallel, protect shared account balances, and avoid deadlocks. Inputs guarantee that every transfer is valid regardless of execution order.
Signature: def apply_transfers(balances, transfers):
Input: balances is a dictionary from account ID to integer balance. transfers is a list of transfer triples.
Output: Return a new dictionary containing final balances, without mutating the input dictionary.
Examples: {"A": 100, "B": 50}, [["A", "B", 30]] returns {"A": 70, "B": 80}. Two transfers involving the same account must still produce the correct combined balance.
def apply_transfers(balances, transfers):