nix
nix copied to clipboard
Mutex
Added a mutex interface.
What is the advantage of pthread mutexes compared to std::sync::Mutex ?
std::sync::Mutex is not repr(C) and thus has inconsistent members ordering so can't be used between Rust processes (e.g. processes sharing a mutex stored in shared memory) and it can't be used for FFI.
This is a very low-level, C-ish API.
The goal is to allow the flexibility I need, this does unfortunately make it quite low level.
- Mutex::unlock can trigger UB within the pthread library
- There are no mutex guards, so the programmer must remember to manually unlock the mutex.
I have used a guard mechanism for Mutex::lock and marked Mutex::unlock as unsafe.
- The mutex doesn't protect any data. That's the
Tinstd::sync::Mutex<T>. So the programmer must remember which data the mutex is supposed to protect. That's even more awkward in Rust than in C, because the protected data is probably accessed via a shared immutable pointer which the programmer must unsafely cast.
The problem is that Rust doesn't allow changing representation of imported structs. I require repr(C) to use it across-process but this is less efficient repr(Rust), people would want both.
We could add:
struct MutexWrapperReprC<T> {
lock: Mutex,
data: UnsafeCell<T>,
}
struct MutexWrapperReprRust<T> {
lock: Mutex,
data: UnsafeCell<T>,
}
// etc.
But this seems quite awkward.
Have you looked at the https://github.com/glandium/flexible-locks library yet? It might already do what you want.
I did not know about this. I will look at this.
I think it is still valuable to have Mutex in Nix (especially given https://github.com/glandium/flexible-locks appears to no longer be maintained).
The problem is that Rust doesn't allow changing representation of imported structs. I require
repr(C)to use it across-process but this is less efficientrepr(Rust), people would want both.
Is it really that much less efficient? I think repr(C) would probably satisfy. And it's certainly far better than no RAII at all.
The problem is that Rust doesn't allow changing representation of imported structs. I require
repr(C)to use it across-process but this is less efficientrepr(Rust), people would want both.Is it really that much less efficient? I think
repr(C)would probably satisfy. And it's certainly far better than no RAII at all.
To be honest, I have never seen it make a difference but I guess LLVM implemented struct re-ordering for a reason.