Mutex and ManualResetEvent

Hi all,

What are the differences between ManualResetEvent class and Mutex class

Thanks,
Suresh.





Answer this question

Mutex and ManualResetEvent

  • Ken_Hosinski

    Thanks .

    I want to learn more on how mutexes achieve Thread synchronization between processes in .NET.Can you provide some links for articles,sample codes etc for the same.

    Thanks,
    Suresh.

  • Lyn Perkins

    Hi Heath,

    I tried the following code to request owning the Mutex object while creation.



    using System;
    using System.Diagnostics;
    using System.Threading;

    class MutexExample
    {
        static void Main(string[] args)
        {
            Mutex mutex = new Mutex(true,"MyMutex");

            if (args.Length > 0 && args[0] == "1")
            {
                Console.WriteLine("Second process started.");
                mutex.WaitOne();
                Console.WriteLine("Second process exiting.");
            }
            else
            {
                Console.WriteLine("First process started.");
                Process.Start(Environment.GetCommandLineArgs()[0], "1");
                mutex.WaitOne();
                Thread.Sleep(5000);
                Console.WriteLine("First process exiting.");
                mutex.ReleaseMutex(); 
            }
            Console.ReadLine();
        }
    }

     


    But after the ReleaseMutex is executed in the first process,the Second Process doesnt get the Mutex object.It waits until the first process is killed.Now,if i put false while creating the Mutex object,the second process gets the Mutex object after executing ReleaseMutex in first process.Why is this

    Does the Mutexes identifies the object based on the name alone Where the CreateMutex stores the name of mutexes

    Is it not a big security vulnerability to identify and implement Mutexes based on name alone Its' ok that we can keep the name very safe., but there are chances that some 2 applications may end up in creating same Mutex name unknowingly.It will make both the applications to work in a unpredicatble way,and more worse,its very difficult to find the root cause for that.

    Thanks,
    Suresh.


  • Hajimu Takahashi

    The big differences are how they are used. For one, a ManualResetEvent requires that you call ManualResetEvent.Reset() to unsignal the event; otherwise, any attempt to pass it to WaitHandle.Wait() or WaitHandle.WaitAll() would not block. The AutoResetEvent class would be more akin to Mutex since once you signal the event the AutoResetEvent is automatically unsignalled.

    Any thread can signal the event while only a single thread can own a mutex and release that mutex. That is, one thread cannot release the mutex owned by another thread.

    Also, you can specify named mutexes while you can't specified named events.

    The classes also use different native constructs. The Mutex class ultimately ends up calling the native CreateMutex API, while the two event classes call the native CreateEvent API.

    Events are a means of controlling program flow between threads while mutexes are to synchronize threads.

  • davidhart_home

    Synchronizing applications against a named mutex is no different than synchronizing two different threads. Mutexes are valid for the system or current user (see http://msdn.microsoft.com/library/en-us/dllproc/base/createmutex.asp for details) so you can create a named mutex in each application and synchronize against it. Below is an example that starts the same EXE twice (so two different processes).


    using System;
    using System.Diagnostics;
    using System.Threading;

    class MutexExample
    {
     static void Main(string[] args)
     {
      Mutex mutex = new Mutex(false, "MutexExample");

      if (args.Length > 0 && args[0] == "1")
      {
       Console.WriteLine("Second process started.");
       mutex.WaitOne();
       Console.WriteLine("Second process exiting.");
      }
      else
      {
       Console.WriteLine("First process started.");
       Process.Start(Environment.GetCommandLineArgs()[0], "1");
       mutex.WaitOne();
       Thread.Sleep(5000);
       Console.WriteLine("First process exiting.");
      }
     }
    }

     



  • Alistair Black

    Ah, right. Sorry. :)

    I'm not sure why you can't create a named event in .NET since even Win95 supports named events, but you could either extend WaitHandle with your own class to P/Invoke CreateEvent or use different named Mutex instances. It's a stretch of the Mutex class but should still yield the results you're looking for.

  • rosnay

    The second process waits when specifying that the first process is the initial owner of the mutex because the call to ReleaseMutex() only releases the mutex once. You have requested ownership twice in the same thread: 1) when creating it and initially requesting ownership, and 2) when you call WaitOne().

    Also, you should create the process while you own the mutex (even if passing false as the first parameter to the Mutex() constructor). Granted, you'll probably never run into a case where the new process is started before WaitOne() is called, but best not take such a chance.

    Regarding security, you do have the potential for a denial of service (DoS) attach if someone uses the same name. You can mitigate this vulnerability under certain scenarios by setting access control for the mutex. Read http://msdn2.microsoft.com/library/System.Threading.Mutex.SetAccessControl for details. This really would only work to protect a mutex running under one context (user, machine, etc.) from another.

    On Terminal Server, you can also prefix the name with Global\ or Local\ to allow the mutex to apply to all users connected to Terminal Server or to just a single user. This is only supported on Windows 2000 and newer.

    See the documentation for the native CreateMutex() function for more information.

  • Tony Chun Tung Siu

    In your first reply of this thread...you told this..

    "Also, you can specify named mutexes while you can't specified named events."

    Thanks,
    Suresh.


  • anand_nalya

    Thanks.

    Since we cannot use named Events how can Events control program flow across threads in differenet processes

    Thanks again,
    Suresh.


  • smartpi

    Why can't you use named events If you don't use named events, you'll have to create inheritable events which will require you to P/Invoke CreateEvent to pass it with a SECURITY_ATTRIBUTES reference with bInheritHandle set to true. That means, then, that your processes must be related in that they are all children or parents of each other and that the event was created in the eldest parent.

  • Mutex and ManualResetEvent