Why are Rust's `Cell` and `RefCell` not `Sync`, and what does `UnsafeCell`, the type both are built on, provide?
answer
- plain, non-atomic updates
- &RefCell would have to be Send
- Send yes, Sync no
- the only legal opt-out for &T
- casting &T to &mut T is UB
basics
~20 sCell and RefCell mutate through &T with plain, non-atomic operations, so two threads sharing one could race on the value or RefCell's borrow counter; std therefore marks them !Sync. Both wrap UnsafeCell, the only legal way to mutate data behind a shared reference.
solid answer
~40 s`core::cell` declares `impl<T: ?Sized> !Sync for Cell<T>` and the same for `RefCell<T>`, while both are `Send` when `T: Send`. You may move a cell to another thread, but not share `&RefCell` between threads. `RefCell`'s borrow counter is a plain `Cell<isize>`: two threads calling `borrow_mut()` together could both read zero and both get a `RefMut`, two aliasing `&mut T`, which is undefined behaviour. rustc enforces this with E0277, "`RefCell<Vec<i32>>` cannot be shared between threads safely", and suggests `std::sync::RwLock`. Underneath, both wrap `UnsafeCell<T>`: the compiler normally assumes data behind `&T` does not change, and `UnsafeCell` is the one type that opts out, giving a `*mut T` through `get()`. Casting `&T` to `&mut T` yourself is undefined behaviour, and rustc rejects the direct cast with the deny-by-default `invalid_reference_casting` lint.
code
rust · 11 linesuse std::cell::RefCell;
use std::thread;
fn main() {
let cache = RefCell::new(vec![1, 2, 3]);
thread::scope(|s| {
s.spawn(|| cache.borrow_mut().push(4));
s.spawn(|| cache.borrow_mut().push(5));
});
println!("{:?}", cache.borrow());
}go deeper
Recall that Cell and RefCell are single-threaded: they can be moved into a thread but not shared by reference between threads.
Explain Send versus Sync for the cells, and that RefCell's counter is a plain Cell<isize> whose read-check-write would race between threads.
Read the E0277 chain from the captured &RefCell back to the missing Sync, and pick the right thread-safe replacement instead of reaching for unsafe impl Sync.
Explain why std keeps cells cheap by making them !Sync and leaving synchronisation to separate types, and what that split means for code that may later go multi-threaded.
## What `Sync` means for a cell In Rust, a type is **`Send`** if a value of it can be moved to another thread, and **`Sync`** if a `&T` to it can be used from several threads at once. The precise rules and the auto-trait machinery belong to the material on `Send` and `Sync`; here the point is which of the two a cell can honestly promise. The standard library answers in `core/src/cell.rs`: - `unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}` - `impl<T: ?Sized> !Sync for Cell<T> {}` - `unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}` - `impl<T: ?Sized> !Sync for RefCell<T> {}` So a cell is **Send but not Sync**. Moving a `RefCell<Vec<i32>>` into a spawned thread is fine, because only that thread can reach it afterwards. Handing two threads a `&RefCell<Vec<i32>>` is rejected. ## Why the borrow counter cannot be shared `RefCell<T>` stores its state in an ordinary `Cell<isize>`: zero for unused, positive for live `Ref` guards, negative for a live `RefMut`. `borrow_mut()` reads the counter, checks it is zero, and writes the new state. Those are separate, unsynchronised operations. If two threads shared one cell, this interleaving would be possible: 1. Thread A reads the counter: zero. 2. Thread B reads the counter: zero. 3. Both write "mutably borrowed" and both receive a `RefMut`. 4. Two `&mut T` to the same value now exist, which is **undefined behaviour**, and their writes race. `Cell<T>` has the same problem without a counter: `set` and `get` are plain writes and reads, and concurrent unsynchronised access is a data race. The module documentation states the rule directly: the cell types allow mutation "in a single-threaded way" and "do not implement `Sync`". The compiler turns this into an error rather than a runtime surprise. Sharing a `RefCell` between two `thread::scope` tasks produces E0277, "`RefCell<Vec<i32>>` cannot be shared between threads safely", with the notes that `&RefCell<Vec<i32>>` must be `Send` for the closure to be spawned and that `std::sync::RwLock` is the type for aliasing and mutation across threads. | Type | `Send` (move to a thread) | `Sync` (share `&` across threads) | |---|---|---| | `Cell<T>` | when `T: Send` | never | | `RefCell<T>` | when `T: Send` | never | | `UnsafeCell<T>` | when `T: Send` | never | | `Rc<RefCell<T>>` | never (`Rc` is `!Send`) | never | ## `UnsafeCell<T>`: the primitive underneath The standard library calls `UnsafeCell<T>` "the core primitive for interior mutability in Rust". Its role: - Normally the compiler optimises on the assumption that **data behind `&T` is immutable**. Mutating such data, whether through an alias or by transmuting `&T` into `&mut T`, is undefined behaviour. - `UnsafeCell<T>` opts out of that guarantee: a `&UnsafeCell<T>` may point to data that is being mutated. The Rust Reference states it is the only allowed way to disable the requirement. - Its API is minimal: `get(&self) -> *mut T`. Turning that pointer into references soundly is the job of whoever builds on it. - It does **not** make data races safe; the docs say they "are still undefined behavior", and `UnsafeCell` is itself `!Sync`. - It changes nothing about `&mut`: a `&mut UnsafeCell<T>` must still be unique. `Cell<T>` and `RefCell<T>` are safe wrappers that keep the promise `UnsafeCell` asks for. `Cell` never lends a reference into its contents, so every mutation is a whole-value copy or move on one thread. `RefCell` lends references but uses its counter to guarantee a `&mut T` is never aliased. `Cell<T>` is `#[repr(transparent)]` over `UnsafeCell<T>`, so the safety costs nothing in layout. Writing new abstractions on `UnsafeCell` with raw pointers is unsafe-code territory, covered with sound safe abstractions. ## What you cannot do instead The tempting shortcut is to skip the cell and cast: ```rust let me = unsafe { &mut *(self as *const Counter as *mut Counter) }; ``` This is undefined behaviour even if nothing else reads the value, because `self` is a `&Counter` to data without an `UnsafeCell`. rustc rejects it with the deny-by-default `invalid_reference_casting` lint: "casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell`". The fix is to put the mutable field in a `Cell` or `RefCell`, or, across threads, in an atomic, `Mutex`, `RwLock` or `OnceLock`.
- Why does the E0277 message talk about `&RefCell` needing to be `Send`?The scoped-thread closure captures `cache` by reference, and `spawn` requires the closure to be `Send`. A closure is `Send` only if its captures are, and a `&T` is `Send` only when `T` is `Sync`. `RefCell` is `!Sync`, so the captured `&RefCell<Vec<i32>>` is not `Send` and the spawn is rejected.
- Does `UnsafeCell` make shared mutation across threads safe?No. It only tells the compiler that data behind a shared reference may change. The docs say data races through it are still undefined behaviour, and `UnsafeCell` is itself `!Sync`. Thread-safe types such as atomics, `Mutex` and `RwLock` build synchronisation on top of it.
- How can `Cell<T>` be sound with no counter at all?It never lends a reference into its contents. Every operation copies or moves a whole value in or out, so no `&T` exists that a `set` could invalidate. Being `!Sync` guarantees all those operations happen on one thread, so they cannot interleave.
- RefCell is not Send, so it cannot be moved to another thread at all.
- Wrapping a RefCell in Rc makes it safe to share across threads.
- RefCell's borrow counter is atomic, so sharing it only costs speed.
- UnsafeCell prevents data races by itself.
- Casting &T to &mut T in an unsafe block is fine if nothing else reads it.