Skip to content

Instantly share code, notes, and snippets.

@omer-biz
Created February 6, 2023 11:02
Show Gist options
  • Save omer-biz/a9385eb9edc51f1bffb686a7bd1cef0c to your computer and use it in GitHub Desktop.
Save omer-biz/a9385eb9edc51f1bffb686a7bd1cef0c to your computer and use it in GitHub Desktop.
Deadlock
let resource_one = Arc::new(Mutex::new(10));
let resource_two = Arc::new(Mutex::new(20));
let r1 = resource_one.clone();
let r2 = resource_two.clone();
let th1 = thread::spawn(move || {
let mut r2 = r2.lock().unwrap();
thread::sleep(Duration::from_secs(5));
let mut r1 = r1.lock().unwrap();
*r1 += 1;
*r2 += 5;
println!("th1: have got both r1: {}, and r2 {}", r1, r2);
});
let r1 = resource_one.clone();
let r2 = resource_two.clone();
let th2 = thread::spawn(move || {
let mut r1 = r1.lock().unwrap();
thread::sleep(Duration::from_secs(5));
let mut r2 = r2.lock().unwrap();
*r1 += 2;
*r2 += 3;
println!("th2: have got both r1: {}, and r2 {}", r1, r2);
});
th1.join().unwrap();
th2.join().unwrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment