Expand description
Re-entrant lock manager that prevents multiple threads or processes from concurrently holding a lock on the same resource. I’m using it to mimic transactions in a database, but it could be used for other things too. It’s LLM generated and I don’t really understand all of it. Works on a best-effort basis; it’s likely to be flaky on network filesystems, FUSE, non-POSIX OSes, etc.
Guarantees, in principle:
- Mutual exclusion across threads for a given (
resource_type, id). - Re-entrant acquisition by the SAME thread won’t deadlock (recursion counter).
- OS-level advisory file lock held exactly once while any logical acquisitions exist.
- Other threads attempting acquisition block until the owning thread fully releases (recursion -> 0).
Design:
- Global table:
(resource_type, id)->Arc<ResourceLockEntry>. ResourceLockEntrycontains(Mutex<LockState>, Condvar).LockState:- owner:
Option<ThreadId> - recursion: usize (depth for current owner)
- refcount: usize (number of active
ResourceLockhandles – across all threads) - file:
Option<File>(file whose lifetime == OS lock lifetime)
- owner:
Acquisition steps (ResourceLock::acquire):
- Lookup/insert entry in global table.
- Lock the entry’s state.
- If no owner: set owner = current thread, recursion = 1, refcount += 1.
- If file is None: open + lock file (OS lock).
- Else if owner == current thread: recursion += 1; refcount += 1.
- Else wait on Condvar until owner released (recursion == 0), then loop.
Drop:
- Lock state, decrement recursion and refcount.
- If recursion == 0: owner = None;
notify_all()to wake waiters. - If refcount == 0: drop file (releases OS lock) and remove entry from table. Also remove the lock file on disk.
Structs§
- Lock
State 🔒 - Resource
Lock - Acquire a lock for a given resource type and id.
Guarantees mutual exclusion across threads for a given (
resource_type, id). Re-entrant acquisition by the same thread is allowed. - Resource
Lock 🔒Entry
Statics§
Traits§
Functions§
- check_
filesystem_ lock_ support - get_
inode_ or_ file_ index - get_
inode_ or_ file_ index_ from_ descriptor - lock_
table 🔒 - path_
and_ descriptor_ match
Type Aliases§
- LockKey 🔒