Loading RustViz Engine...
Transfer funds between two accounts locking in consistent pointer/id memory order.
This problem is currently in blueprint template mode. Once the concept foundation is finalized, live in-browser WebAssembly compilation and test assertion runners will be enabled here.
use std::sync::Mutex;
pub struct Account { pub id: u64, pub balance: Mutex<i64> }
pub fn transfer(from: &Account, to: &Account, amount: i64) {
// Acquire locks in ascending id order to guarantee deadlock freedom
if from.id < to.id {
let mut b1 = from.balance.lock().unwrap();
let mut b2 = to.balance.lock().unwrap();
*b1 -= amount; *b2 += amount;
} else {
let mut b2 = to.balance.lock().unwrap();
let mut b1 = from.balance.lock().unwrap();
*b1 -= amount; *b2 += amount;
}
}