download

Why do concurrent transfers deadlock, and how do you prevent it?

Systems~10 minReviewed 2 Dec 2026Free · No sign-in

Question

Two threads move funds between account A (id 1, balance 100) and account B (id 2, balance 100). Thread 1 runs transfer(&a, &b, 30) while Thread 2 runs transfer(&b, &a, 10). Under load, both threads freeze forever.

  1. Trace the exact steps that freeze both threads.
  2. Fix transfer using global lock ordering, including the self-transfer case (from.id == to.id).
  3. How does try_lock with backoff differ from global lock ordering?
"CODE · RUST"
struct Account { id: u32, bal: Mutex<i64> }

fn transfer(from: &Account, to: &Account, amt: i64) {
    let mut g1 = from.bal.lock().unwrap();
    let mut g2 = to.bal.lock().unwrap();
    *g1 -= amt;
    *g2 += amt;
}
Show hints (3)
  1. "OPPOSITE LOCK ORDER"

    Thread 1 locks A first and waits for B. What is Thread 2 holding and waiting for at the exact same moment?

  2. "ONE SHARED RULE"

    If every thread locks the lower account ID before the higher ID, can a cycle ever form?

  3. "SAME ACCOUNT TWICE"

    std::sync::Mutex is not reentrant. What happens if someone calls transfer(&a, &a, 10)?

Show checked explanation

Thread 1 locks A while Thread 2 locks B, then each blocks forever waiting for the other lock (circular wait). Fix it by returning early when from.id == to.id and always locking the smaller account ID first. Global lock ordering prevents cycles outright, whereas try_lock breaks them by backing off and retrying.

"SOLUTION · RUST"
use std::{sync::Mutex, thread};
struct Account { id: u32, bal: Mutex<i64> }

fn transfer(from: &Account, to: &Account, amt: i64) {
    if from.id == to.id { return; }
    let (lo, hi) = if from.id < to.id { (from, to) } else { (to, from) };
    let mut g1 = lo.bal.lock().unwrap();
    let mut g2 = hi.bal.lock().unwrap();
    let d = if from.id < to.id { amt } else { -amt };
    (*g1, *g2) = (*g1 - d, *g2 + d);
}
fn main() {
    let a = Account { id: 1, bal: Mutex::new(100) };
    let b = Account { id: 2, bal: Mutex::new(100) };
    thread::scope(|s| {
        s.spawn(|| transfer(&a, &b, 30));
        transfer(&b, &a, 10);
    });
    println!("a={} b={}", a.bal.lock().unwrap(), b.bal.lock().unwrap());
}
"OUTPUT"
a=80 b=120

Compiled and ran the lock-ordered transfer, stress test, self-transfer check, and circular-wait try_lock probe with rustc 1.94.1 on Windows x64. Checked by an editor other than the author.

Walkthrough

Deadlock needs four conditions at once: exclusive locks, holding one lock while waiting for another, no forced preemption, and a circular wait. Here is how the starter triggers that cycle:

stepthread 1 (A -> B)thread 2 (B -> A)
1Locks A (succeeds)Locks B (succeeds)
2Calls B.lock(), blocksCalls A.lock(), blocks
3Waiting on Thread 2 foreverWaiting on Thread 1 forever

Global lock ordering breaks the circular wait. Every call picks (lo, hi) with lo.id < hi.id and acquires lo first, then hi. Now both transfer(&a, &b, 30) and transfer(&b, &a, 10) lock account 1 first and account 2 second. Whichever thread wins account 1 acquires account 2 next, updates both balances, and drops both guards at the end of transfer. Final balances are always a=80 and b=120.

The guard if from.id == to.id { return; } stops a subtle single-thread deadlock: Rust's Mutex is not reentrant, so locking the same account twice hangs that thread forever.

How try_lock with backoff differs: instead of blocking on the second lock, you call to.bal.try_lock(). If it returns WouldBlock, you drop the first lock, pause briefly with random jitter, and retry. That works when you cannot define a global order ahead of time, but under heavy contention threads can repeatedly yield to each other (livelock) or starve without jittered backoff.

Common mistakes

  • Skipping the from.id == to.id check. Locking the same non-reentrant Mutex twice deadlocks a single thread immediately.
  • Ordering locks by pointer address works only when one in-memory object represents each resource. Separate wrappers for the same database row or moving-GC runtimes break address order; use a stable id.
  • Retrying try_lock in a tight loop without dropping the first lock or adding jitter. Holding the first lock still deadlocks, and synchronized retries cause livelock.
  • Using one global mutex around every transfer in a huge system. It prevents deadlock, but serializes unrelated transfers like C -> D behind A -> B.

Follow-up questions

  • "What if a transfer needs to lock three accounts, or a dynamic list of accounts?" Sort the unique account IDs first, deduplicate them, and lock them in strictly ascending order. The same proof holds: no thread holding a higher ID can ever wait on a lower ID.
  • "What happens in Rust if a thread panics while holding a.bal.lock()?" The guard still drops during unwinding and releases the OS lock, so other threads do not hang. Rust marks the Mutex as poisoned, causing future .lock() calls to return Err(PoisonError) so callers notice potentially half-updated state.
  • "How do you diagnose a live deadlock in production?" Capture stack traces from all threads (for example with gdb, lldb, or runtime thread dumps). Look for two or more threads parked inside mutex lock calls where each thread owns a mutex another thread is waiting on.

What a strong answer covers

Traces the two-thread circular wait, enforces ascending ID lock order, handles self-transfers cleanly, and compares deterministic lock ordering against try_lock backoff and livelock risk.

Open in interactive practice deck →

Original OfferVibe question. std::sync::Mutex.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.