with_lock

Deadlock freedom

Using with_lock? Share it in the discussion!

Docs

Example

Say you have this code:

```rust,no_run 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(); asserteq!(*alock + b_lock, 5); let a_lock_2 = a.lock().unwrap(); let b_lock_2 = b.lock().unwrap(); assert_eq!(alock2 + *block2, 5); } `` That code will run the firstasser_eq!` fine, but the second wouldn't assert due to a deadlock.

However, we can prevent this by replacing our manual calls of .lock with .with_lock. Code that wouldn't error would look something like:

```rust use std::sync::Mutex; use with_lock::WithLock;

fn main() { let a = WithLock::::new(2); let b = WithLock::::new(3); let alock = a.withlock(|s| *s); let block = b.withlock(|s| *s); asserteq!(alock + block, 5); let alock2 = a.withlock(|s| *s); let block2 = b.withlock(|s| *s); asserteq!(alock2 + block2, 5); } ```

This test would pass, and both assertions would be fulfilled. This is an example of how a dead lock was prevented.

Cell like API

with_lock provides a custom Cell like API powered by a Mutex.

```rust use with_lock::MutexCell;

fn main() { let a = MutexCell::new(2); let b = MutexCell::new(3); let alocked = a.get(); let blocked = b.get(); asserteq!(alocked + blocked, 5); let alock2 = a.get(); let block2 = b.get(); asserteq!(alock2 + block2, 5); } ```

For more examples, see the examples directory. They can be run by cloning this repository and running cargo run --example <example_name>.