Module resource_lock

Source
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>.
  • ResourceLockEntry contains (Mutex<LockState>, Condvar).
  • LockState:
    • owner: Option<ThreadId>
    • recursion: usize (depth for current owner)
    • refcount: usize (number of active ResourceLock handles – across all threads)
    • file: Option<File> (file whose lifetime == OS lock lifetime)

Acquisition steps (ResourceLock::acquire):

  1. Lookup/insert entry in global table.
  2. Lock the entry’s state.
  3. If no owner: set owner = current thread, recursion = 1, refcount += 1.
    • If file is None: open + lock file (OS lock).
  4. Else if owner == current thread: recursion += 1; refcount += 1.
  5. 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§

LockState 🔒
ResourceLock
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.
ResourceLockEntry 🔒

Statics§

MODEL_LOCK_TABLE 🔒

Traits§

Lock

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 🔒