pub struct HzrdReader<'cell, T> { /* private fields */ }
Expand description
A reader object for a specific HzrdCell
The HzrdReader
holds a reference to the value of the HzrdCell
, as well as a HzrdPtr
to read from it. When performing many, consecutive reads of a cell this can be much more performant, as you only need to retrieve the HzrdPtr
once.
§Basic usage
The basics of using a HzrdReader
is to first create a HzrdCell
, and then call the reader
method on the cell to retrieve a reader.
let cell = HzrdCell::new(false);
std::thread::scope(|s| {
s.spawn(|| {
let mut reader = cell.reader();
while !reader.get() {
std::hint::spin_loop();
}
println!("Done!");
});
s.spawn(|| {
std::thread::sleep(Duration::from_millis(1));
cell.set(true);
});
});
§The elephant in the room
The keen eye might have observed some of the “funkiness” with HzrdReader
in the previous example: Reading the value requires a mutable/exclusive reference, and thus the reader must be marked as mut
. Note also that this was not the case for reading, or even writing (!), to the cell itself. Exclusivity is usually associated with mutation, but for the HzrdReader
this is not the case. The reason that reading via a HzrdReader
requires a mutable/exclusive reference is that the reader holds access to only a single hazard pointer. This hazard pointer is used when you read a value, so as long as you hold on the value read that hazard pointer is busy.
let cell = HzrdCell::new([0, 1, 2]);
// NOTE: The reader must be marked as mutable
let mut reader = cell.reader();
// NOTE: We use associated function syntax here to
// emphasize the need for a mutable reference
let handle = HzrdReader::read(&mut reader);
assert_eq!(handle[0], 0);
Implementations§
Source§impl<T> HzrdReader<'_, T>
impl<T> HzrdReader<'_, T>
Sourcepub fn read(&mut self) -> ReadHandle<'_, T>
pub fn read(&mut self) -> ReadHandle<'_, T>
Read the associated value and return a handle holding a reference it
Note that the reference held by the returned handle is to the value as it was when it was read. If the cell is written to during the lifetime of the handle this will not be reflected in its value.
§Example
let cell = HzrdCell::new(String::new());
let mut reader = cell.reader();
let string = reader.read();
assert!(string.is_empty());