pub trait RegionCachedExt<T> {
// Required methods
fn with_cached<F, R>(&self, f: F) -> R
where F: FnOnce(&T) -> R;
fn set_global(&self, value: T);
}Expand description
Extension trait that adds convenience methods to region-cached static variables
in a region_cached! block.
Required Methods§
Sourcefn with_cached<F, R>(&self, f: F) -> R
fn with_cached<F, R>(&self, f: F) -> R
Executes the provided function with a reference to the cached value in the current memory region.
§Example
use region_cached::{region_cached, RegionCachedExt};
region_cached!(static FAVORITE_COLOR: String = "blue".to_string());
let len = FAVORITE_COLOR.with_cached(|color| color.len());
assert_eq!(len, 4);Sourcefn set_global(&self, value: T)
fn set_global(&self, value: T)
Publishes a new value to all memory regions.
The update will be applied to all memory regions in a weakly consistent manner.
§Example
use region_cached::{region_cached, RegionCachedExt};
region_cached!(static FAVORITE_COLOR: String = "blue".to_string());
FAVORITE_COLOR.set_global("red".to_string());Updating the value is weakly consistent. Do not expect the update to be immediately visible. Even on the same thread, it is only guaranteed to be immediately visible if the thread is pinned to a specific memory region.
use many_cpus::SystemHardware;
use region_cached::{region_cached, RegionCachedExt};
use std::num::NonZero;
region_cached!(static FAVORITE_COLOR: String = "blue".to_string());
// We can use this to pin a thread to a specific processor, to demonstrate a
// situation where you can rely on consistency guarantees for immediate visibility.
let one_processor = SystemHardware::current()
.processors()
.to_builder()
.take(NonZero::new(1).unwrap())
.unwrap();
one_processor.spawn_thread(move |processor_set| {
let processor = processor_set.processors().first();
println!("Thread pinned to processor {} in memory region {}",
processor.id(),
processor.memory_region_id()
);
FAVORITE_COLOR.set_global("red".to_string());
// This thread is pinned to a specific processor, so it is guaranteed to stay
// within the same memory region (== on the same physical hardware). This means
// that an update to a region-cached value is immediately visible.
let color = FAVORITE_COLOR.with_cached(|color| color.clone());
assert_eq!(color, "red");
}).join().unwrap();Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".