-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
Some time ago, a discussion on Reddit made me think about how one can do ordered locks of Rust mutexes. Sadly, it seems it can't be done right now, because there exists no interface that would let order mutexes. Hence, I propose the following changes to the Mutex API. The first two are independent of each other, but still related enough that I think they can be put in the same RFC.
1. PartialOrd implementation for Mutex
Add the following trait implementations:
impl<T1: ?Sized, T2: ?Sized> PartialEq<Mutex<T2>> for Mutex<T1> { ... }
impl<T: ?Sized> Eq for Mutex {}
impl<T1: ?Sized, T2: ?Sized> PartialOrd<Mutex<T2>> for Mutex<T1> { ... }
impl<T: ?Sized> Ord for Mutex { ... }
This will allow comparing any mutexes of any type with each other. The implementations will use the address of inner
box for comparisons, which guarantees strict ordering even when mutexes are moved. The downside is that Mutex would then have to guarantee strict order forever.
2. Expose native mutex handle
This will allow to use native OS API for whatever purpose, and also allow to share mutexes through FFI. Also, in case PartialOrd idea gets rejected, it will allow to implement equivalent functionality outside of sync
module, or even in 3rd-party crate. I don't think there are any downsides to this idea, except for usual subjective feelings of API bloat and exposing guts of implementation.
3. ordered_lock!
macro
If either of the above ideas get implemented, the next step would be to provide an easy and ergonomic API for ordered locking - due to lack of variadic generics in current Rust, the next best thing is a macro that takes arbitrary number of mutexes as arguments and returns a tuple of MutexGuard
s. Of course it can be implemented in 3rd-party crate just as well.