expression

Consistent lock ordering: prevent circular waiting

When operations need multiple locks, establish and enforce one global acquisition order. This removes circular wait among those locks if every participant obeys the policy. Other causes of deadlock can remain. Expected stdout (not executed): 3 4 Common mistake: Taking A then B in one path and B then A in another.

Formal Syntax & Structure

rust syntaxrust
acquire A before B in every path

Working Example

Example Snippetrust
fn main() {    use std::sync::Mutex;    let a = Mutex::new(1); let b = Mutex::new(2);    std::thread::scope(|s| {        for _ in 0..2 { s.spawn(|| { let mut x = a.lock().unwrap(); let mut y = b.lock().unwrap(); *x += 1; *y += 1; }); }    });    println!("{} {}", a.into_inner().unwrap(), b.into_inner().unwrap());}
Rust Reference