Advertisement



< Prev
Next >



C# Synchronization



There could be a conflict when two or more running threads need to access a shared resource such as in-memory data (instance or class variables) and external objects such as files, at the same time, which could lead to data anomalies or inconsistent data.

C# language provides us a smooth access of such shared resource by a process of synchronization, which ensures that only one thread is accessing the shared resource at a time, preventing the other thread from doing the same at the same time, thereby avoiding the possible conflict between threads.




How synchronization is achieved?


Synchronization is achieved by using the feature of lock, which locks the access to a block of code within the locked object. When a thread locks an object, no other thread can access a block of code within the locked object. Only when a threads releases the lock over the object, it is available for other thread to access it.

In C#, every object has a built-in lock. By using the feature of Synchronization, we can lock an object. Locking an object can be done by using the lock keyword, and its general form is shown below.

lock(object)
{
	//Statement1
	//Statement2
	//And more statements to be synchronized
}

When a thread acquires the lock over an object, it gets sole access to the block of statements within the locked object. Now, all the other threads wishing to access this block of statements within the same locked object will have to wait until, the thread that has got the lock on the object, releases the lock, by exiting the block of statements.

Before we show you an example of how to use the synchronization between threads by locking an object and its practical use, let us show you what actually happens without using synchronization on executing multiple threads, whuch are trying to access a same resource.



Unsynchronized run of multiple threads.


We are creating three threads that are going to compete over executing a same method. The first thread to enter the method does not get its sole access, this thread executes the method for a while before it is replaced another thread wanting to execute this method as well.

//C# Example of Synchronization

using System;
using System.Threading;

class B
{
public void meth()
{
	for(int i=0;i<3;i++)
	{
		Console.WriteLine(Thread.CurrentThread.Name +" is printing " + i);
	}

}
}


class ThreadEx
{
Thread thread;

//Constructor of our class
public ThreadEx(String name, B ob)
{

	//Creating a new thread, based on the object of ThreadEx class
	//Which is referred by 'this' reference
	//We are also specifying the entry-point method that will be called to begin the execution of our thread.
	thread = new Thread(this.Run);

	//Setting the name of a thread by using the Name property of Thread
	thread.Name = name;

	//Calling the Start() method, which calls the entry-point method defined with an argument
	//And passing it an argument i.e. object of the B class
	thread.Start(ob);
}


//Entry Point of the new thread.
public void Run(Object ob)  
{
	//Getting the reference to the currently executing thread.
	Thread th = Thread.CurrentThread;

	//Casting the value of count(which was internally an int), from Object to int
	B obj =(B)ob;
	

	Console.WriteLine(th.Name + " has started its execution");

	//Using the object of B class to call the meth() method 
	obj.meth();

	Console.WriteLine(th.Name + " has finished its execution ");


}


public static void Main(String[] ar)
{
	//Creating an object of B class
	B ob = new B();

	//Creating three objects of our ThreadEx class
	//where each object is used to construct a separate thread
	//And all three objects are using the same object of B class
	ThreadEx ob1 = new ThreadEx("My Thread1", ob);
	ThreadEx ob2 = new ThreadEx("My Thread2", ob);
	ThreadEx ob3 = new ThreadEx("My Thread3", ob);
}
}

Output is - :

My Thread1 has started its execution
My Thread2 has started its execution
My Thread2 is printing 0
My Thread1 is printing 0
My Thread1 is printing 1
My Thread1 is printing 2
My Thread1 has finished its execution
My Thread3 has started its execution
My Thread3 is printing 0
My Thread3 is printing 1
My Thread3 is printing 2
My Thread3 has finished its execution
My Thread2 is printing 1
My Thread2 is printing 2
My Thread2 has finished its execution


Program Analysis





Advertisement




Synchronized run of multiple threads.


We are creating three threads that are going to compete over executing a same method, but this time access to this method will be synchronized because we are going to use the lock, to lock the object within which the method is going to be accessed by multiple threads.

The first thread to enter the method gets its sole access until it exits the method, thereby avoiding the collision between two threads competing for a method.

//C# Example of Synchronization

using System;
using System.Threading;

class B
{
public void meth()
{
	for(int i=0;i<3;i++)
	{
		Console.WriteLine(Thread.CurrentThread.Name +" is printing " + i);
	}

}
}


class ThreadEx
{
Thread thread;

//Constructor of our class
public ThreadEx(String name, B ob)
{

	//Creating a new thread, based on the object of ThreadEx class
	//Which is referred by 'this' reference
	//We are also specifying the entry-point method that will be called to begin the execution of our thread.
	thread = new Thread(this.Run);

	//Setting the name of a thread by using the Name property of Thread
	thread.Name = name;

	//Calling the Start() method, which calls the entry-point method defined with an argument
	//And passing it an argument i.e. object of the B class
	thread.Start(ob);
}


//Entry Point of the new thread.
public void Run(Object ob)  
{
	//Getting the reference to the currently executing thread.
	Thread th = Thread.CurrentThread;

	//Casting the object referenced, ob(which was internally an object of B class), from Object to B
	B obj =(B)ob;
	
	// Locking the object of B class
	//In other words, synchronizing the access to the object of B class
	lock(obj)
	{
		Console.WriteLine(th.Name + " has started its execution");
		obj.meth();
		Console.WriteLine(th.Name + " has finished its execution ");
	}

}


public static void Main(String[] ar)
{
	//Creating an object of B class
	B ob = new B();

	//Creating three objects of our ThreadEx class
	//where each object is used to construct a separate thread
	//And all three objects are using the same object of B class
	ThreadEx ob1 = new ThreadEx("My Thread1", ob);
	ThreadEx ob2 = new ThreadEx("My Thread2", ob);
	ThreadEx ob3 = new ThreadEx("My Thread3", ob);
}
}


Output is - :


My Thread1 has started its execution
My Thread1 is printing 0
My Thread1 is printing 1
My Thread1 is printing 2
My Thread1 has finished its execution
My Thread2 has started its execution
My Thread2 is printing 0
My Thread2 is printing 1
My Thread2 is printing 2
My Thread2 has finished its execution
My Thread3 has started its execution
My Thread3 is printing 0
My Thread3 is printing 1
My Thread3 is printing 2
My Thread3 has finished its execution


Program Analysis




Note: The first thread to enter the method meth() over the locked object of B class, get its sole access and once this thread has finished its execution of the method, only then it is replaced by another thread which has got the lock over the object, thereby by using the feaure of synchronization by using lock, we can avoid a conflict between threads wishing to access the same resource.



Please share this article -




< Prev
Next >
< C# Thread Abort() Method
C# Interthread Communication >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement