Showing posts with label lock. Show all posts
Showing posts with label lock. Show all posts

Monday, December 5, 2011

Mutex - Threading



Mutex ensures only one thread can enter particular section. Mutex is similar to lock statement the only difference is that Mutex can work across multiple processes while lock can work only for multiple threads. Mutex ensures only one process (application) can run at a time. Mutex is slower than lock. We can use WaitOne method to acquire lock and ReleaseMutex to release lock.

There are two types of mutex available, named and unnamed. Unnamed mutex are called as local mutex and available within your process. Only threads inside your process can access it. While named mutex are visible throughout the operating system and multiple processes can be able to access it. Checkout Mutex page on MSDN for more information.    

Let’s understand with simple example.

public static Mutex mutex = new Mutex();
public static void DoWork()
{
        mutex.WaitOne();

        Console.WriteLine("Thread {0} has entered", Thread.CurrentThread.Name);

        Thread.Sleep(2000);

        Console.WriteLine("Thread {0} is leaving", Thread.CurrentThread.Name);

        mutex.ReleaseMutex();
}
public static void Main()
{
       for (int i = 0; i < 3; i++)
        {
            Thread t1 = new Thread(new ThreadStart(DoWork));
            t1.Name = "Thread " + i.ToString();
            t1.Start();
        }
}     


As demonstrated in above code, WaitOne method requests to acquire a lock and ReleaseMutex method request to release lock. Mutex can only be released by the thread that acquired it. The main method creates three threads one by one and tries to access DoWork method. DoWork method implements mutex so only one thread at a time will able to access. 

Monitor.Enter/Monitor.Exit - Threading



Monitor.Enter and Monitor.Exit provides exclusive locking and ensures only one thread enters inside monitor block at a time. Lock statement internally uses Monitor.Enter and Monitor.Exit with try/finally block.

public class MyClass
{
       static int a=12, b=4;
       static object obj =new Object();
       public static void Divide()
       {
              Monitor.Enter(obj);
              try {
                     if (b != 0)
                           Console.WriteLine("{0} / {1} = {2}", a, b, a/b);
                     b = 0;
              }
              finally
              {
                     Monitor.Exit(obj);
              }
       }
       public static void Main()
       {
              Thread t1 = new Thread(new ThreadStart(Divide));
              t1.Start();
       }
}


As demonstrated in above code, when one thread enters Monitor.Enter block, other threads are trying to enter inside block at same time are queued in ready queue until first thread call Monitor.exit statement similar to lock statement.

In some scenario with multithreaded application, once Monitor.Enter acquires lock and due to some exception not able to enter try/finally block in this case lock will not be released and cause memory leaked. Dotnet 4.0 has the solution for the same, added overload Monitor.Enter method. It takes referenced boolean value along with locked object. If lock is acquired, the overloaded boolean value returns true. Let’s see how it works.

static int a = 12, b = 4;
static object obj = new Object();
static bool isLocked = false;
public static void Divide()
{
    Monitor.Enter(obj,ref isLocked);
    try
    {
        if (b != 0)
            Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
        b = 0;
    }
    finally
    {
        if (isLocked)
        {
            Monitor.Exit(obj);
        }
    }
}

As per above code if lock is acquired successfully then isLocked variable's value set to true and we can release lock if isLocked value is true. If lock is not acquired isLocked value remains false.



See Also - 

Lock statement - Threading

When two or more threads are accessing shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread can enter at a time. Exclusive locking ensure only one thread at a time can enter inside lock section. Lock is simple and faster to implement in multithreading. Let’s have a look below example.

public class MyClass
{
       static int a=12, b=4;
       public static void Divide()
       {
              if (b != 0)
                     Console.WriteLine("{0} / {1} = {2}", a, b, a/b);
              b = 0;
       }
       public static void Main()
       {
              Divide();           
       }
}


If Divide method was called by two threads at a time, there might be possibility to get divide by zero exception. Now let’s have a look on below modified code with lock statement.

static int a=12, b=4;
       static object obj =new Object();
       public static void Divide()
       {
              lock(obj)
              {
                     if (b != 0)
                           Console.WriteLine("{0} / {1} = {2}", a, b, a/b);
                     b = 0;
              }
       }

The above code is now thread-safe. Lock statement ensures only one thread can enter inside lock block. If one thread acquired lock and the same time other thread tries to enter the lock block, the lock will put another thread in ready queue. When first thread release lock another thread from ready queue will enter the lock block.