Struct range_lock::VecRangeLock[][src]

pub struct VecRangeLock<T> { /* fields omitted */ }
Expand description

General purpose multi-thread range lock for Vec<T>.

Example

use range_lock::VecRangeLock;
use std::sync::{Arc, Barrier};
use std::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);

let thread0 = thread::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]
    }
});

let thread1 = thread::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]
    }
});

thread0.join().expect("Thread 0 failed");
thread1.join().expect("Thread 1 failed");

let data = Arc::try_unwrap(data_lock2).expect("Arc unwrap failed").into_inner();

assert_eq!(data, vec![100, 11, 200, 13]);

Implementations

Construct a new VecRangeLock.

  • data: The data Vec to protect.

Get the length (in number of elements) of the embedded Vec.

Unwrap the VecRangeLock into the contained data. This method consumes self.

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

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.