Loading…
Loading…
Three accounts, A, B, and C, start with the given balances. Multiple worker threads concurrently process this fixed list of transfers, repeated 10 times:
1A -> B 100
2B -> C 50
3C -> A 30
4A -> C 70
5B -> A 20
6C -> B 40Print the final balances of A, B, and C, space-separated.
Why this is gradable. Concurrent code can legitimately produce different interleavings on every run, so this practice bank only includes problems whose correctness reduces to one deterministic final value or invariant — never a specific thread ordering. If your solution is correct, it will print the exact same output on every run, no matter how the scheduler interleaves your threads. Money is conserved regardless of execution order — the sum
A + B + Cnever changes, and since the transfer list and repeat count are fixed, the final individual balances are also fixed. That's the invariant this problem is really testing: transferring money between two locked accounts must be atomic, without deadlocking.
Input: 1000 1000 1000
Output: -200 1700 1500
(Balances can go negative here — there's no overdraft check, this problem is purely about safe concurrent transfers, not business rules.)
A transfer needs to lock both the source and destination account so the debit and credit happen atomically. But if thread 1 locks A then waits for B, while thread 2 locks B then waits for A, you get a deadlock — both threads wait forever.
Always acquire the two accounts' locks in a fixed, consistent order (e.g. alphabetically by account name), regardless of which account is the source and which is the destination. If every thread agrees on the same lock order, circular waits become impossible.
1def do_transfer(frm, to, amount):
2 first, second = sorted([frm, to])
3 with locks[first]:
4 with locks[second]:
5 balances[frm] -= amount
6 balances[to] += amountLine 1: three space-separated integers — initial balances of A, B, C
Print the final balances, space-separated, in the order A B C.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.