distkit
Locks

RwLock

A writer-preferring distributed reader-writer lock.

RwLock allows many concurrent readers or a single writer, across processes. It is writer-preferring: once a writer is waiting, new readers queue behind it, so a steady stream of readers can't starve a writer.

It mirrors tokio::sync::RwLock. Read guards and write guards are distinct types, both pure access tokens.

Construct

use distkit::{DistkitRedisKey, lock::{RwLock, LockOptions}};

let key = DistkitRedisKey::try_from("config_blob".to_string())?;
let rw = RwLock::new(LockOptions::new(key, conn));

Read side

use std::time::Duration;

let r = rw.read().await?;                                  // wait for shared access
let r = rw.try_read().await?;                              // one non-blocking attempt
let r = rw.try_read_for(Duration::from_secs(2),
                        Duration::from_millis(50)).await?; // bounded wait

r.release().await?; // or drop it

Multiple readers can hold the lock at the same time:

let r1 = rw.try_read().await?;
let r2 = rw.try_read().await?; // both succeed
r1.release().await?;
r2.release().await?;

Write side

let w = rw.write().await?;                                  // exclusive
let w = rw.try_write().await?;
let w = rw.try_write_for(Duration::from_secs(2),
                         Duration::from_millis(50)).await?;

w.release().await?;

A writer waits for all current readers to clear, and while it waits, no new reader is admitted.

Guards

Both RwLockReadGuard and RwLockWriteGuard expose the same lifecycle methods as the mutex guard - get_state() to inspect the lease and release() to release explicitly. See Guard state & errors.