Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explain the use of UnsafeCell in Mutex #54

Merged
merged 1 commit into from
Oct 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading