Named std::sync::Mutex?

Is it possible using safe rust to create a named mutex with behavior similar to CreateMutexA from the win32 api wrapper as seen here?

https://docs.rs/winapi/0.3.7/winapi/um/synchapi/fn.CreateMutexA.html

I was looking at std::sync::Mutex and didn’t see any way to create a mutex with a name that is unique between all applications. I’m guessing because this is a win32 api call it probably isn’t supported with safe rust, but I figured I’d check to see if anyone knows of a safe way to do this.

I imagine this is because not all operating systems will support naming a mutex, and std is meant to be a cross-platform abstraction over the OS.

Additionally looking at libstd/sys/windows/mutex.rs on GitHub, it seems like Rust’s mutex actually uses critical sections on Windows and not the normal mutex which can be used for inter-process synchronisation.

I’m not too familiar with synchronisation in winapi, but I’m guessing this was done because not needing to communicate with other processes is faster?

2 Likes

Critical sections are indeed the Windows API primitive that maps closest to what most languages and platforms call “mutex”, the Windows API naming is a bit abnormal.

A Windows “mutex” is a somewhat heavy interprocess primitive and is probably not suitable for the kind of synchronization that a language’s mutex would do.

One could probably make a separate crate around the named Windows mutex and SysV primitives to provide it in a kind-of portable manner, but it’d kind of have to leverage some sort of underlying platform functionality to do so. Pretty much everything that interacts with the world has some inner unsafety - you just have to properly handle it as a module author.

3 Likes

Thanks for the info. I was mainly looking for a way to ensure that only one instance of my application could run at a time. It seems like there’s a lot of overhead with a Windows “mutex”. I took another look at the documentation for CreateMutexA and they mention you can achieve the same result with a locked file.

If anyone is curious about the solution, I ended up using the fs2 crate to lock a file and end new instances if the file is locked.

https://docs.rs/fs2/0.4.3/fs2/
https://docs.rs/fs2/0.4.3/fs2/trait.FileExt.html#tymethod.try_lock_exclusive

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.