Struct atomic_immut::AtomicImmut
[−]
[src]
pub struct AtomicImmut<T> { /* fields omitted */ }
A thread-safe pointer for immutable value.
This is a thin container. Each AtomicImmut
instance has an immutable value.
After the AtomicImmut
instance is created,
it is not possible to modify a part of the contained value.
But you can replace the value entirely with another value.
AtomicImmut
is useful for sharing rarely updated and
complex (e.g., hashmap) data structures between threads.
Examples
use std::collections::HashMap; use std::sync::Arc; use std::thread; use atomic_immut::AtomicImmut; let mut map = HashMap::new(); map.insert("foo", 0); let v = Arc::new(AtomicImmut::new(map)); { let v = v.clone(); thread::spawn(move || { let mut new = (&*v.load()).clone(); new.insert("bar", 1); v.store(new); }); } while v.load().len() == 1 {} assert_eq!(v.load().get("foo"), Some(&0)); assert_eq!(v.load().get("bar"), Some(&1));
Methods
impl<T> AtomicImmut<T>
[src]
fn new(value: T) -> Self
[src]
Makes a new AtomicImmut
instance.
fn load(&self) -> Arc<T>
[src]
Loads the value from this pointer.
Examples
use atomic_immut::AtomicImmut; let value = AtomicImmut::new(5); assert_eq!(*value.load(), 5);
fn store(&self, value: T)
[src]
Stores a value into this pointer.
Examples
use atomic_immut::AtomicImmut; let value = AtomicImmut::new(5); assert_eq!(*value.load(), 5); value.store(1); assert_eq!(*value.load(), 1);
fn update<F>(&self, f: F) where
F: for<'a> Fn(&'a T) -> T,
[src]
F: for<'a> Fn(&'a T) -> T,
Updates the value of this pointer by calling f
on the value to get a new value.
The function f
may be called more than once when there is a conflict with other threads.
Examples
use atomic_immut::AtomicImmut; let value = AtomicImmut::new(5); assert_eq!(*value.load(), 5); value.update(|v| *v * 2); assert_eq!(*value.load(), 10);
fn swap(&self, value: T) -> Arc<T>
[src]
Stores a value into this pointer, returning the old value.
Examples
use atomic_immut::AtomicImmut; let value = AtomicImmut::new(5); assert_eq!(*value.load(), 5); let old = value.swap(1); assert_eq!(*value.load(), 1); assert_eq!(*old, 5);