critical-section icon indicating copy to clipboard operation
critical-section copied to clipboard

Why UnsafeCell in Mutex?

Open skibon02 opened this issue 5 months ago • 4 comments

The core idea of a mutex is to make !Sync types Sync. This is exactly what this line does https://github.com/rust-embedded/critical-section/blob/3a328a84040b721034a1b084e4a9dea8218a90f8/src/mutex.rs#L191

!Sync type == cannot function properly when used concurrently behind shared references.

To fulfill the safety contract we must guarantee that all shared access to the inner type is synchronized. From the perspective of critical sections, fulfillment of the safety contract depends only on proper handling of lifetimes, because while owning a valid CriticalSection<'cs>, any shared access to inner type is safe.

There is no actual benifit to using UnsafeCell here, and the only requirement is to ensure that shared access to the inner type bound by 'cs lifetime.

As I ran some tests, it seems like additional UnsafeCell layer does not cause any performance regressions. But if we change it to just T, curious people like me will have fewer questions regarding necessity of such wrappers :)

skibon02 avatar Sep 16 '24 07:09 skibon02