[Day9] Read Rust Atomics and Locks — Mutex, RwLock, Atomics and UnsafeCell
At Topics: Chapter 1. Basics of Rust Concurrency
Extension of interior mutability
Recall
RefCell
std::cell::RefCell<T>
- Unlike
Cell
, it allows you to borrow its contents (callborrow()
orborrow_mut()
)
use std::cell::RefCell;
fn f(v: &RefCell<Vec<i32>>) {
// We can modify the `Vec` directly.
v.borrow_mut().push(1);
}
- It has a counter for outstanding (未處理的) borrows
- It can only be used within a single thread
Notes
Mutex and RwLock
- An
RwLock
or reader-writer lock is the concurrent version of aRefCell
- An
RwLock<T>
holds aT
and tracks any outstanding borrows - When conflicting borrows happen, it does not
panic
. Instead, it blocks the current thread (putting it to sleep) and waits for conflicting borrows to disappear. - Borrowing the contents of an `RwLock` is called locking
RwLock
keeps tracking shared and exclusive borrows- A
Mutex
is very similar toRwLock
, but it only allows exclusive borrows
Atomics
- While an
RwLock
is the concurrent version of aRefCell
, The atomic types represent the concurrent version of aCell
- They cannot be of arbitrary size, so there is no
Atomic<T>
- Usually use
AtomicU32
andAtomicPtr<T>
(depends on the processor)
UnsafeCell
- An
UnsafeCell
is the primitive building unit for interior mutability - No restrictions to avoid undefined behavior
- Can only be used in
unsafe
block - Commonly, an
UnsafeCell
is wrapped in another type that provides safety through a limited interface, such asCell
orMutex
. - In other words, all types with interior mutability are built on top of
UnsafeCell
, Including:Cell
,RefCell
,RwLock
,Mutex
…