Skip to main content

routee_compass_core/util/
read_only_lock.rs

1use std::sync::{Arc, LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard};
2
3///
4/// there are no read-only locks in the existing rust library
5/// that prevent executors from having write access. this pair
6/// of classes allows a driver application to instantiate a RwLock
7/// on an object, and then issue read-only clones of that lock to
8/// executors in a parallel setup.
9///
10/// see https://stackoverflow.com/a/68908523
11///
12pub struct DriverReadOnlyLock<T> {
13    inner: Arc<RwLock<T>>,
14}
15
16impl<T> DriverReadOnlyLock<T> {
17    pub fn new(val: T) -> Self {
18        Self {
19            inner: Arc::new(RwLock::new(val)),
20        }
21    }
22
23    pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
24        self.inner.write()
25    }
26
27    pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
28        self.inner.read()
29    }
30
31    pub fn read_only(&self) -> ExecutorReadOnlyLock<T> {
32        ExecutorReadOnlyLock {
33            inner: self.inner.clone(),
34        }
35    }
36}
37
38pub struct ExecutorReadOnlyLock<T> {
39    inner: Arc<RwLock<T>>,
40}
41
42impl<T> ExecutorReadOnlyLock<T> {
43    pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
44        self.inner.read()
45    }
46}