From 762c0a87462fa23c7b52190a600a05b10a8a7d79 Mon Sep 17 00:00:00 2001 From: Jan Niehusmann Date: Thu, 19 Sep 2024 14:48:23 +0000 Subject: [PATCH] Explain the use of UnsafeCell in Mutex --- src/mutex.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/mutex.rs b/src/mutex.rs index c9ea6ff..9f6088b 100644 --- a/src/mutex.rs +++ b/src/mutex.rs @@ -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 { + // 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, }