pub struct VecRangeLock<T> { /* private fields */ }
Expand description
General purpose multi-thread range lock for std::vec::Vec.
§Example
use range_lock::VecRangeLock;
use std::{sync::{Arc, Barrier}, thread};
let data = vec![10, 11, 12, 13];
let data_lock0 = Arc::new(VecRangeLock::new(data));
let data_lock1 = Arc::clone(&data_lock0);
let data_lock2 = Arc::clone(&data_lock0);
// Thread barrier, only for demonstration purposes.
let barrier0 = Arc::new(Barrier::new(2));
let barrier1 = Arc::clone(&barrier0);
thread::scope(|s| {
s.spawn(move || {
{
let mut guard = data_lock0.try_lock(0..2).expect("T0: Failed to lock 0..2");
guard[0] = 100; // Write to data[0]
}
barrier0.wait(); // Synchronize with second thread.
{
let guard = data_lock0.try_lock(2..4).expect("T0: Failed to lock 2..4");
assert_eq!(guard[0], 200); // Read from data[2]
}
});
s.spawn(move || {
{
let mut guard = data_lock1.try_lock(2..4).expect("T1: Failed to lock 2..4");
guard[0] = 200; // Write to data[2]
}
barrier1.wait(); // Synchronize with first thread.
{
let guard = data_lock1.try_lock(0..2).expect("T1: Failed to lock 0..2");
assert_eq!(guard[0], 100); // Read from data[0]
}
});
});
let data = Arc::try_unwrap(data_lock2).expect("Arc unwrap failed").into_inner();
assert_eq!(data, vec![100, 11, 200, 13]);
Implementations§
Source§impl<'a, T> VecRangeLock<T>
impl<'a, T> VecRangeLock<T>
Sourcepub fn new(data: Vec<T>) -> VecRangeLock<T>
pub fn new(data: Vec<T>) -> VecRangeLock<T>
Construct a new VecRangeLock.
data
: The data Vec to protect.
Sourcepub fn into_inner(self) -> Vec<T>
pub fn into_inner(self) -> Vec<T>
Unwrap this VecRangeLock into the contained data. This method consumes self.
Sourcepub fn try_lock(
&'a self,
range: impl RangeBounds<usize>,
) -> TryLockResult<VecRangeLockGuard<'a, T>>
pub fn try_lock( &'a self, range: impl RangeBounds<usize>, ) -> TryLockResult<VecRangeLockGuard<'a, T>>
Try to lock the given data range
.
- On success: Returns a VecRangeLockGuard that can be used to access the locked region.
Dereferencing VecRangeLockGuard yields a slice of the
data
. - On failure: Returns TryLockError::WouldBlock, if the range is contended. The locking attempt may be retried by the caller upon contention. Returns TryLockError::Poisoned, if the lock is poisoned.
Trait Implementations§
Source§impl<T: Debug> Debug for VecRangeLock<T>
impl<T: Debug> Debug for VecRangeLock<T>
impl<T> Sync for VecRangeLock<T>where
T: Send,
Auto Trait Implementations§
impl<T> !Freeze for VecRangeLock<T>
impl<T> !RefUnwindSafe for VecRangeLock<T>
impl<T> Send for VecRangeLock<T>where
T: Send,
impl<T> Unpin for VecRangeLock<T>
impl<T> UnwindSafe for VecRangeLock<T>where
T: RefUnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more