pub trait RegionLocalExt<T> {
// Required methods
fn with_local<F, R>(&self, f: F) -> R
where F: FnOnce(&T) -> R;
fn set_local(&self, value: T);
}Expand description
Extension trait that adds convenience methods to region-local static variables
in a region_local! block.
Required Methods§
Sourcefn with_local<F, R>(&self, f: F) -> R
fn with_local<F, R>(&self, f: F) -> R
Executes the provided function with a reference to the value stored in the current memory region.
§Example
use region_local::{region_local, RegionLocalExt};
region_local!(static FAVORITE_COLOR: String = "blue".to_string());
let len = FAVORITE_COLOR.with_local(|color| color.len());
assert_eq!(len, 4);Sourcefn set_local(&self, value: T)
fn set_local(&self, value: T)
Publishes a new value to all threads in the current memory region.
The update will be applied to all threads in the current memory region in a weakly consistent manner. The updated value will not be visible in other memory regions - storage is independent for each memory region.
§Example
use region_local::{region_local, RegionLocalExt};
region_local!(static FAVORITE_COLOR: String = "blue".to_string());
FAVORITE_COLOR.set_local("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::ProcessorSet;
use region_local::{region_local, RegionLocalExt};
use std::num::NonZero;
region_local!(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 = ProcessorSet::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_local("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-local value is immediately visible.
let color = FAVORITE_COLOR.with_local(|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", so this trait is not object safe.