Prevent deadlocks
Say you have this code:
```rs use std::sync::Mutex;
fn main() {
let a = Mutex::new(2);
let b = Mutex::new(3);
let alock = a.lock().unwrap();
let block = b.lock().unwrap();
println!("{:?}", *alock + *block);
let alock2 = a.lock().unwrap();
let block2 = b.lock().unwrap();
println!("{:?}", *alock2 + *block2);
}
``
That code will log
5` once, when it should log twice. As you can see here, it is deadlocking.
However, we can prevent this by replacing our manual calls of .lock
with .with_lock
. So code that wouldn't error would look something like:
```rs use std::sync::Mutex; use with_lock::WithLock;
fn main() {
let a = WithLock::
That code would log 5
twice. This is an example of how it can prevent deadlocks.