Monday, December 5, 2011

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.



No comments:

Post a Comment