Skip to content

Commit

Permalink
Explain the use of UnsafeCell in Mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
jannic committed Sep 19, 2024
1 parent 3a328a8 commit 762c0a8
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ use core::cell::{Ref, RefCell, RefMut, UnsafeCell};
/// [interior mutability]: https://doc.rust-lang.org/reference/interior-mutability.html
#[derive(Debug)]
pub struct Mutex<T> {
// The `UnsafeCell` is not strictly necessary here: In theory, just using `T` should
// be fine.
// However, without `UnsafeCell`, the compiler may use niches inside `T`, and may
// read the niche value _without locking the mutex_. As we don't provide interior
// mutability, this is still not violating any aliasing rules and should be perfectly
// fine. But as the cost of adding `UnsafeCell` is very small, we add it out of
// cautiousness, just in case the reason `T` is not `Sync` in the first place is
// something very obscure we didn't consider.
inner: UnsafeCell<T>,
}

Expand Down

0 comments on commit 762c0a8

Please sign in to comment.