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?

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/ 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?


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.


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.


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