`lock_api::RawMutex` implementation based on `std`

Recently, I was in need of an implementor of lock_api::RawMutex and I was surprised to find that there is no implementation based on std available. Indeed, I could not find any suitable implementation at all and had to cobble together my own futex based lock. This of course limits portability. I looked at these options:

  • spin: I sometimes use a cooperative thread scheduler (hermit), so this does not work
  • parking_lot: This allocates. I plan to use the mutex in an allocator (possibly the global allocator). So this also does not work.
  • implement in terms of std: std only has the guard based api, so I cannot keep the mutex locked without storing the guard somewhere.

Basically, std implements a mutex exactly how I would want it, just with a too high level api. Therefore, my preferred solution would be for std to offer a more raw api for mutex so that lock_api could be implemented on top of it. What would be the process for making that happen?

All of this probably applies to RwLock as well, though I have not looked too far into that.

2 Likes

Are you sure that RawMutex in parking_lot - Rust allocates? According to Mutex in parking_lot - Rust it isn't boxed.

It allocates in its internal parking hash map: parking_lot/core/src/parking_lot.rs at master · Amanieu/parking_lot · GitHub

The std Mutex also allocates on among other platforms macOS. It uses thread mutexes there, which are not allowed to be moved, while Mutex can be moved.

1 Like

Interesting, #93740 gave me the impression that all platforms managed to do mutexes without allocation, but it seems that goal was dropped in favor of other goals. This kills my use case for the proposed lower level apis.

For anyone stumbling upon this thread in the future: rustix-futex-sync provides a (linux only) futex based implementation of RawMutex and other traits.