3 releases
| 0.1.2 | Mar 29, 2023 |
|---|---|
| 0.1.1 | Mar 21, 2023 |
| 0.1.0 | Mar 20, 2023 |
#1740 in Concurrency
183 downloads per month
Used in 2 crates
(via shukusai)
10KB
69 lines
RoLock
Read Only Lock.
This is a wrapper around Arc<RwLock<T>> that only implements RwLock::read() operations.
Usage
Create a normal Arc<RwLock<T>> in thread_1, send a RoLock to thread_2:
let rw = Arc::new(RwLock::new(0)); // Regular Arc<RwLock<T>>.
let ro = RoLock::new(&rw); // Read Only Lock.
assert!(*rw.read().unwrap() == 0); // This can read...
*rw.write().unwrap() = 1; // and write.
std::thread::spawn(move|| {
assert!(*ro.read().unwrap() == 1); // This one can only read.
});
thread_1still has full read/write controlthread_2can onlyRoLock::read()
This type guarantees at compile time that you cannot write because the function doesn't even exist:
let rw = Arc::new(RwLock::new(0));
let ro = RoLock::new(&rw);
ro.write(); // Compile error!
Since the inner field of RoLock (self.0) is private, you can't call RwLock::write directly either:
let rw = Arc::new(RwLock::new(0));
let ro = RoLock::new(&rw);
ro.0.write(); // Compile error!