Skip to content

Commit

Permalink
Merge pull request #54 from jannic/document-unsafecell-in-mutex
Browse files Browse the repository at this point in the history
Explain the use of UnsafeCell in Mutex
  • Loading branch information
Dirbaio authored Oct 16, 2024
2 parents a5f0c36 + 762c0a8 commit 91e8b9e
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 91e8b9e

Please sign in to comment.