pub struct SnapshotLock<T, Inner = RwLock<(T, usize)>> { /* private fields */ }Expand description
A versioned lock implementation inspired by Multi-Version Concurrency Control (MVCC).
SnapshotLock provides concurrent access to data with lock-free reads and exclusive writes.
It maintains multiple versions of the data to allow readers to access consistent
snapshots without blocking writers.
§Type Parameters
T: The type of data being protected. Must beClone. Surrounding lock isSendandSyncifTisSend
§Examples
use snaplock::SnapshotLock;
let lock = SnapshotLock::new(String::from("Hello"));
// Multiple readers can access the data concurrently
let reader1 = lock.read();
let reader2 = lock.read();
assert_eq!(*reader1, "Hello");
assert_eq!(*reader2, "Hello");
// Writers have exclusive access
let mut writer = lock.write();
writer.push_str(", World!");
// During write readers see old values
let reader3 = lock.read();
assert_eq!(*reader3, "Hello");
drop(writer);
// When write is finished, new readers see the updated value
let reader4 = lock.read();
assert_eq!(*reader4, "Hello, World!");
// Old readers still see their old value
assert_eq!(*reader1, "Hello");
assert_eq!(*reader2, "Hello");
assert_eq!(*reader3, "Hello");Implementations§
Source§impl<T: Clone> SnapshotLock<T, RwLock<(T, usize)>>
impl<T: Clone> SnapshotLock<T, RwLock<(T, usize)>>
Sourcepub fn write(
&self,
) -> SnapshotLockWriteGuard<'_, T, RwLockWriteGuard<'_, (T, usize)>>
pub fn write( &self, ) -> SnapshotLockWriteGuard<'_, T, RwLockWriteGuard<'_, (T, usize)>>
Acquires an exclusive write lock on the protected data.
This method blocks until no other writers hold the lock. The returned
SnapshotLockWriteGuard allows mutable access to the data. When the guard is
dropped, the version number is incremented and subsequent reads will
see the updated value.
§Returns
A SnapshotLockWriteGuard that provides mutable access to the data.
§Examples
use snaplock::SnapshotLock;
let lock = SnapshotLock::new(0);
{
let mut guard = lock.write();
*guard = 42;
} // Guard dropped here, version incremented
assert_eq!(*lock.read(), 42);Sourcepub fn read(&self) -> SnapshotLockReadGuard<T>
pub fn read(&self) -> SnapshotLockReadGuard<T>
Acquires a shared read lock on the protected data.
This method attempts to get the latest version of the data with minimal blocking. It first tries a non-blocking read of the current version, and if that fails or detects a newer version, it falls back to a cached snapshot.
§Returns
A SnapshotLockReadGuard that provides immutable access to a snapshot of the data.
§Examples
use snaplock::SnapshotLock;
let lock = SnapshotLock::new("data");
let guard = lock.read();
assert_eq!(*guard, "data");