How to protect shared object in multi threading by lock statement in c#

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 5603 red flag

How to implement locking in multi threading environment.

How to protect shared object in multithreading by lock statement in C# 

Here we will discuss how to protect any object in multithreaded environment. As multithreading is very important concept in modern programming language so we have to learn proper implementation of it.

Before going to example we will discuss what exactly multithreading is and few terminology related to multi threading.

Multithreading: - Multi threading is nothing but parallel processing. Here two or more process can able to execute simultaneously.  But what happen in behind the screen?  Actually single process executes sequentially but switching of process is very fast, so that it illustrate to user that multiple processing is running simultaneously.

Critical section: - It is nothing but a block of code which is sharable across various threads. 

Deadlock: - This is one state of object . In multithreading environment when one process is waiting for one resource and the resource is locked by another process and again that process is waiting for a resource which is locked by another process. And the cycle is in circular fashion.

Mutex :-  A mutex prevent simultaneous execution of code by more than one thread at a time. A mutex can be used to synchronize threads across process.

Lock :- Locking is a mechanism which need to implement to a object before using it in shared environment. For example, we want to share one global object across multiple threads, then before sharing it we lock it and it will ensure that at a time only one thread will work with this object.

Now, we will see simple stricture of locking technique 

using System;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
namespace Test1
{
   class Program
    {
       public object Lock = new object();
      
       public void Function()
       {
           Int32 SensetiveData = 0;
           lock (Lock)
           {
               //Operation with Sensetive Data
           }
 
       }
        static void Main(string[] args)
        {
            Console.ReadLine();
        }
    }
}

This is very basic structure of locking implementation. At first we have created one object using statement.below 

       public object Lock = new object();

Now within Function(), we have define one data member which we want to protect in multi threaded environment. And in next line we have implemented locking mechanism using previously created object.

           lock (Lock)
           {
               //Operation with Sensetive Data
           }

This lock statement will ensure that out sensitive data operation will be safe in multi thread.

Now, in next example we will see how to execute lock section code or critical section code using thread. Have a look on below code.

using System;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
namespace Test1
{
   class Program
    {
       public object LockMe = new object();
       public int Value = 0;
       public void MakeLock()
       {
           lock (LockMe)
           {
               Value += 10;
           }
           Console.WriteLine(Value);
 
       }
 
        static void Main(string[] args)
        {
            Thread[] threads = new Thread[10];
            Program p = new Program();
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(p.MakeLock));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
            Console.ReadLine();
        }
    }
}

Here is output:-


Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)