[Day9] Read Rust Atomics and Locks - Mutex, RwLock, Atomics and UnsafeCell
By Mara Bos
At Topics: Chapter 1. Basics of Rust Concurrency
Extension of interior mutability
Recall
RefCell
-
std::cell::RefCell -
Unlike
Cell, it allows you to borrow its contents (callborrow()orborrow_mut())use std::cell::RefCell; fn f(v: &RefCell<Vec<i32>>) { v.borrow_mut().push(1); // We can modify the `Vec` directly. } -
It has a counter for outstanding (未處理的) borrows
-
It can only be used within a single thread
Notes
Mutex and RwLock
- An
RwLockor reader-writer lock is the concurrent version of aRefCell - An
RwLock<T>holds aTand 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
RwLockis called locking RwLockkeeps tracking shared and exclusive borrows- A
Mutexis very similar toRwLock, but it only allows exclusive borrows.
Atomics
- While an
RwLockis 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
AtomicU32andAtomicPtr<T>(depends on the processor)
UnsafeCell
- An
UnsafeCellis the primitive building unit for interior mutability - No restrictions to avoid undefined behavior
- Can only be used in
unsafeblock - Commonly, an
UnsafeCellis wrapped in another type that provides safety through a limited interface, such asCellorMutex. - In other words, all types with interior mutability are built on top of
UnsafeCell, Including:Cell,RefCell,RwLock,Mutex...