pub trait SyncStrategy<T>: Sized {
// Required methods
fn new(inner: T) -> Self;
fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
}Expand description
A synchronization strategy for providing interior mutability.
This trait abstracts over Mutex<T> (thread-safe) and RefCell<T> (single-threaded)
to allow generic code to work with either synchronization primitive.
§Type Parameters
T- The type being protected by the synchronization primitive
§Examples
use acls_rs::sync::SyncStrategy;
use std::sync::Mutex;
use std::cell::RefCell;
fn use_cache<S: SyncStrategy<Vec<String>>>(cache: &S) -> usize {
cache.with(|data| data.len())
}
// Thread-safe variant
let cache = Mutex::new(vec!["a".to_string()]);
assert_eq!(use_cache(&cache), 1);
// Single-threaded variant
let cache = RefCell::new(vec!["a".to_string()]);
assert_eq!(use_cache(&cache), 1);Required Methods§
Sourcefn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R
fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R
Execute a closure with mutable access to the protected value.
For Mutex, this acquires the lock. For RefCell, this borrows mutably.
§Arguments
f- Closure that receives mutable access to the value
§Returns
The result of the closure
§Panics
For RefCell, panics if already borrowed.
For Mutex, handles poisoned mutexes by logging a warning and recovering.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementations on Foreign Types§
Source§impl<T> SyncStrategy<T> for Mutex<T>
Thread-safe synchronization using Mutex.
impl<T> SyncStrategy<T> for Mutex<T>
Thread-safe synchronization using Mutex.
Automatically handles poisoned mutexes by logging a warning and recovering the inner value. This prevents cascading failures when a thread panics while holding the lock.
Source§impl<T> SyncStrategy<T> for RefCell<T>
Single-threaded synchronization using RefCell.
impl<T> SyncStrategy<T> for RefCell<T>
Single-threaded synchronization using RefCell.
Provides zero-cost interior mutability for single-threaded use cases. Use this variant when you know the type will only be used from one thread.