pub struct SyncCell<T: ?Sized> { /* private fields */ }Expand description
A mutable memory location that can be modified safely from multiple threads.
This structure is similar to std::cell::Cell or std::cell::RefCell
while being thread-safe.
It functions as a thin wrapper around std::sync::RwLock while assuming that poisoned locks
indicate an unrecoverable error. This makes it more ergonomic to use than RwLock at the cost
of some stability.
§As a Cell replacement.
SyncCell can be used to replace the functionality of a std::cell::Cell in contexts where
data need to mutably accessed across multiple threads.
§Using std::cell::Cell
use std::cell::Cell;
let cell = Cell::new(0);
cell.set(1);
println!("{}", cell.get());§Using sync_cell::SyncCell
use sync_cell::SyncCell;
let cell = SyncCell::new(0);
cell.set(1);
println!("{}", cell.get());§As a RefCell replacement.
SyncCell can also be used to replace usages of RefCell.
§Using std::cell::RefCell
use std::cell::RefCell;
let cell = RefCell::new((0, 1));
let borrowed = cell.borrow();
println!("{}", borrowed.0);
drop(borrowed);
let mut mutable_borrow = cell.borrow_mut();
mutable_borrow.1 = 2;
drop(mutable_borrow);
let borrowed = cell.borrow();
println!("{:?}", borrowed);§Using sync_cell::SyncCell
use sync_cell::SyncCell;
let cell = SyncCell::new((0, 1));
let borrowed = cell.borrow();
println!("{}", borrowed.0);
drop(borrowed);
let mut mutable_borrow = cell.borrow_mut();
mutable_borrow.1 = 2;
drop(mutable_borrow);
let borrowed = cell.borrow();
println!("{:?}", borrowed);§Panicking
Unlike std::sync::RwLock, SyncCell will panic rather than return an error when the lock
becomes poisoned.
Implementations§
Source§impl<T> SyncCell<T>
impl<T> SyncCell<T>
Sourcepub const fn new(data: T) -> Self
pub const fn new(data: T) -> Self
Creates a new SyncCell.
data- The initial value of theSyncCell.
Sourcepub fn set(&self, value: T)
pub fn set(&self, value: T)
Sets the value contained in this cell.
value- The new value of the cell.
§Panicking
This method will panic if the lock becomes poisoned.
Sourcepub fn into_inner(self) -> T
pub fn into_inner(self) -> T
Retrieves the inner value stored in this SyncCell.
§Panicking
This method will panic if the lock becomes poisoned.
Source§impl<T: ?Sized> SyncCell<T>
impl<T: ?Sized> SyncCell<T>
Sourcepub fn borrow(&self) -> RwLockReadGuard<'_, T>
pub fn borrow(&self) -> RwLockReadGuard<'_, T>
Borrows a immutable reference to the data stored in this cell.
§Panicking
This method will panic if the lock becomes poisoned.
Sourcepub fn borrow_mut(&self) -> RwLockWriteGuard<'_, T>
pub fn borrow_mut(&self) -> RwLockWriteGuard<'_, T>
Borrows a mutable reference to the data stored in this cell.
§Panicking
This method will panic if the lock becomes poisoned.