#concurrency #thread #locks #mutex

lockpool

This library offers a pool of locks where individual locks can be locked/unlocked by key

6 releases (3 stable)

2.0.1 Oct 16, 2021
2.0.0 Oct 15, 2021
1.0.0 Oct 15, 2021
0.3.0 Oct 15, 2021
0.1.0 Oct 15, 2021

#133 in Concurrency

MIT/Apache

33KB
528 lines

Build Status Latest Version docs.rs License License codecov

lockpool

This library offers a pool of locks where individual locks can be locked/unlocked by key. It initially considers all keys as "unlocked", but they can be locked and if a second thread tries to acquire a lock for the same key, they will have to wait.

use lockpool::LockPool;

let pool = LockPool::new();
let guard1 = pool.lock(4)?;
let guard2 = pool.lock(5)?;

// This next line would cause a deadlock or panic because `4` is already locked on this thread
// let guard3 = pool.lock(4)?;

// After dropping the corresponding guard, we can lock it again
std::mem::drop(guard1);
let guard3 = pool.lock(4)?;

You can use an arbitrary type to index locks by, as long as that type implements PartialEq + Eq + Hash + Clone + Debug.

use lockpool::LockPool;

#[derive(PartialEq, Eq, Hash, Clone, Debug)]
struct CustomLockKey(u32);

let pool = LockPool::new();
let guard = pool.lock(CustomLockKey(4))?;

Under the hood, a LockPool is a HashMap of Mutexes, with some logic making sure there aren't any race conditions when accessing the hash map.

License: MIT OR Apache-2.0

Dependencies

~370–800KB
~19K SLoC

ˆNja