Hard
Two threads locking two mutexes in opposite orders
Thread A locks mutex_a, sleeps, then tries to lock mutex_b. Thread B locks mutex_b, sleeps, then tries to lock mutex_a; the opposite order. No unsafe code is used anywhere. Does this compile, and what happens when it runs?
main.rs
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let mutex_a = Arc::new(Mutex::new(0));
let mutex_b = Arc::new(Mutex::new(0));
let a1 = Arc::clone(&mutex_a);
let b1 = Arc::clone(&mutex_b);
let t1 = thread::spawn(move || {
let _guard_a = a1.lock().unwrap();
thread::sleep(Duration::from_millis(100));
let _guard_b = b1.lock().unwrap(); // waits on mutex_b
});
let a2 = Arc::clone(&mutex_a);
let b2 = Arc::clone(&mutex_b);
let t2 = thread::spawn(move || {
let _guard_b = b2.lock().unwrap();
thread::sleep(Duration::from_millis(100));
let _guard_a = a2.lock().unwrap(); // waits on mutex_a
});
t1.join().unwrap();
t2.join().unwrap();
println!("done");
}34 of 53 in Rust