Struct sublock::atomlock::MainLock [] [src]

pub struct MainLock<T> {
    // some fields omitted
}

A variant of RwLock with sublocks that can be opened for reading iff the main lock is currently opened for reading, opened for writing iff the main lock is currently opened for writing.

use sublock::atomlock::*;

use std::collections::HashMap;
use std::sync::Arc;

struct State {
  live: Arc<Liveness>,
  data: HashMap<usize, SubCell<usize>>
}
impl State {
  fn insert(&mut self, key: usize, value: usize) {
    self.data.insert(key, SubCell::new(&self.live, value));
  }
}

let lock = MainLock::new(|liveness| State {
  live: liveness.clone(),
  data: HashMap::new()
});

{
    println!("* Attempt to read in the MainLock.");
    let guard = lock.read().unwrap();
    assert_eq!(guard.data.len(), 0);
}

{
    println!("* Attempt to write in the MainLock.");
    let mut guard = lock.write().unwrap();
    guard.insert(0, 42);
    assert_eq!(guard.data.len(), 1);
}

{
    println!("* Attempt to read in a SubCell in `read()`.");
    let guard = lock.read().unwrap();
    assert_eq!(guard.data.len(), 1);
    let cell = guard.data.get(&0).unwrap();
    assert_eq!(*cell.borrow(), 42);
}

{
    println!("* Attempt to read and write in a SubCell in `write()`.");
    let guard = lock.write().unwrap();
    assert_eq!(guard.data.len(), 1);
    let cell = guard.data.get(&0).unwrap();
    assert_eq!(*cell.borrow(), 42);

    *cell.borrow_mut() = 99;
    assert_eq!(*cell.borrow(), 99);
}

{
    println!("* Check that the SubCell changes are kept.");
    let guard = lock.read().unwrap();
    assert_eq!(guard.data.len(), 1);
    let cell = guard.data.get(&0).unwrap();
    assert_eq!(*cell.borrow(), 99);
}

Methods

impl<T> MainLock<T>

fn new<F>(cb: F) -> Self where F: FnOnce(&Arc<Liveness>) -> T

fn read(&self) -> LockResult<ReadGuard<T>>

fn try_read(&self) -> TryLockResult<ReadGuard<T>>

fn write(&self) -> LockResult<WriteGuard<T>>

fn try_write(&self) -> TryLockResult<WriteGuard<T>>

fn liveness(&self) -> &Arc<Liveness>

Trait Implementations

impl<T> Drop for MainLock<T>

fn drop(&mut self)