1

Mutex doesn't seem much different than a lock looking at this:

using System.Threading;

class WithMonitor {
  object baton = new object();
  void Method() {
    Monitor.Enter(baton);
    // Work...
    Monitor.Exit(baton);
  }
}

class WithMutex {
  Mutex mutex = new Mutex();
  void Method() {
    mutex.WaitOne();
    // Work...
    mutex.ReleaseMutex();
  }
}

What's the difference?

  • 1
    possible duplicate of [What are the differences between various threading synchronization options in C#?](http://stackoverflow.com/questions/301160/what-are-the-differences-between-various-threading-synchronization-options-in-c) – Greg Mar 04 '15 at 06:19

2 Answers2

-1

Monitor ensures that only one thread at a time can access to the object baton while mutex protects a part of the code.

sithereal
  • 1,656
  • 9
  • 16
  • This isn't a real difference. The `lock` statement, which ensures non-parallel access to a block of code, utilizes a monitor and not a mutex. – Asad Saeeduddin Mar 04 '15 at 06:23
-2

Mutexes, monitors and semaphores are all synchronization mechanisms i.e. they are used to mediate access to a shared resource between multiple processes or threads (referred to as processes henceforth). However, they are used differently:

Mutex:

Used to provide mutual exclusion i.e. ensures at most one process can do something (like execute a section of code, or access a variable) at a time. A famous analogy is the bathroom key in a Starbucks; only one person can acquire it, therefore only that one person may enter and use the bathroom. Everybody else who wants to use the bathroom has to wait till the key is available again.

Monitor:

Provides mutual exclusion to an object i.e. at any point in time, at most one process may access any of the object's members/ execute any of its methods. This is ideologically similar to a mutex for an entire OOP instance*; no part of the instance can be touched by more than one process at a time.

Avisehk
  • 5
  • 1
  • 2
    This looks like an incorrect explanation of what a monitor does. There is no construct in .NET that provides process level isolation for **all** of an object's members. a) Monitors aren't intended to work across process boundaries anyway, and b) unless you specifically write a class with locks in all of its members, a monitor is not going to make it so that only a single thread can access any of the members of an instance. – Asad Saeeduddin Mar 04 '15 at 06:28