Loading…
Loading…
Two accounts, A and B, both start at 1000. One thread continuously transfers 5 from A to B; another thread concurrently and simultaneously transfers 3 from B to A — each running N transfers. Print the final balances of A and B, 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. Each direction runs a fixed number of transfers of a fixed amount, so the net movement is fixed:
Aloses5Nand gains3N;Bloses3Nand gains5N. The final balances are pinned regardless of how the two threads interleave.
Input: N = 200
Output: 600 1400 (A: 1000 - 5(200) + 3(200) = 1000 - 400 = 600; B: 1000 - 3(200) + 5(200) = 1000 + 400 = 1400)
This is the same "lock both accounts" shape as the bank-transfer problem, but with two threads hammering the same pair of accounts in opposite directions simultaneously and continuously — the highest-contention, highest-deadlock-risk shape of this pattern. If your lock ordering isn't rock solid, this is where it shows: either a deadlock (the run hangs and times out) or a lost update (the final numbers come out wrong).
Exactly the fixed-lock-ordering approach from the bank-transfer problem — always acquire the two accounts' locks in the same consistent order (e.g. alphabetically), regardless of transfer direction — but now under sustained, symmetric contention between exactly two threads.
Line 1: N, the number of transfers each direction performs
Print the final balances, space-separated, in the order A B.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.