Skip to content

Ordering mutexes, and retrieving raw mutex handle #2055

@Xirdus

Description

@Xirdus

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 MutexGuards. Of course it can be implemented in 3rd-party crate just as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions