After this thought-provoking post I started to look deeper into Rust memory model and ended up with two questions about UnsafeCell.
I) The documentation is not totally clear to me. One one hand crate-level documentation clearly states
When UnsafeCell is immutably aliased, it is still safe to obtain a mutable reference to its interior and/or to mutate it.
One the other hand get() function documentation states
This can be cast to a pointer of any kind. Ensure that the access is unique when casting to &mut T,
I read it as “Ensure that the write access is unique when casting to &mut T”, is my understanding correct?
II) Both crate level and function level documentation agree that
However, it is up to the abstraction designer to ensure that no two mutable references obtained this way are active at the same time, and that there are no active mutable references or mutations when an immutable reference is obtained from the cell.
ensure that there are no mutations or mutable aliases going on when casting to &T
My question is here is why the order important, how an immutable reference obtained after creating a mutable reference are “worse” than an immutable reference obtained before the mutable? I strongly suspect it related to instruction reordering and cache coherence, but I was not able to construct an example.
Thank you for help!