Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex names - best practice?

Tags:

naming

mutex

Related to this question, what is the best practice for naming a mutex? I realize this may vary with OS and even with version (esp for Windows), so please specify platform in answering. My interest is in Win XP and Vista.

like image 466
Argalatyr Avatar asked Jan 21 '09 06:01

Argalatyr


3 Answers

A really safe name for a global mutex is <a description> + <a GUID>:

MyApp Single Instance Mutex : {c96f7db4-d743-4718-bef0-8533a198bcca}

By using a name like this there is absolutely no chance someone else will use the same mutex name as your mutex.

Sniffing around with process explorer, you can see that GUIDs are used in a few places, though in general they are not used. A pattern that does emerge though is that the word "mutex" is used quite a lot and Microsoft seem to like using capitols.

like image 67
Sam Saffron Avatar answered Sep 25 '22 21:09

Sam Saffron


Suggestion:

Incorporate the object type (Mutex in this case) and application Namespace into the unique name. This will generally be safe. If you want to really be safe then append a Guid as well.

Example:

    string mutexName = "MUTEX: Skyz.Messaging.ThreadPooling.MyAppSingleInstance";

Advantages:

By creating a naming convention for your apps you make it easy to manage many object names, create more readable code and will make it very easy for existing and future developers to understand the code.

Tip:

Instead of using a Mutex Directly in your code write a reusable wrapper class that can make the code more maintainable in case you ever want to change the implementation or add a tweak. Remember to Remove the Mutex using a disposable pattern or you will have issues!

using (SingletonProcess singletonProcess = new SingletonProcess("MUTEX: Skyz.Apps.MessagingQueue.InstanceMarker"))
        {
            if (singletonProcess.IsDuplicateInstance)
            {
                ConsoleWriter.WriteColorLine("An instance of the ExporterService exists, you cannot start a second instance.");
return  


            }
like image 40
Raiford Avatar answered Sep 24 '22 21:09

Raiford


A google search of CreateMutex samples reveals that "MyMutex" is the most common mutex name chosen.

Therefore you should name your mutex "NotMyMutex" to guarantee uniqueness.

like image 36
Chris Becke Avatar answered Sep 24 '22 21:09

Chris Becke