Does a reentrant mutex violate Rust's borrow rules?

I know there is a private implementation of ReentrantMutex in Rust which is not published for public use. Given that it may expose multiple mutable references to the object in a thread while preventing data race in multithreaded programs, should it be considered as a rule violation?

Yes, and that's why the ::parking_lot's reentrant mutex only allows to access &T. You may ask why do we even need a mutex which doesn't allows &mut T, but it allows to share !Sync types between threads so you can wrap it either Cell/RefCell.

4 Likes

Another way to think about this is that any Rust object that is not internally wrapped in an UnsafeCell can have at most one active writeable reference at a time. That is because Rust enables code-motion and code-coalescing operations in the LLVM backend for everything except UnsafeCell. Anytime those optimizations are enabled on any object with two or more active writeable references is instant UB, because LLVM's input constraints have been violated.

Any UB in the program gives LLVM permission to scramble the program arbitrarily – what you would call a miscompilation – in its quest for hyper-optimization. The resulting compilation output is forever unreliable and may fail immediately, or at anytime that your code, a supporting library, or the compiler itself has changed in any way.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.