For this C# thread synchronization interview question, we should be answering need of thread synchronization in C# with program example using with and without synchronization.
Answer:
When sharing of resource i.e. file IO and shared memory etc. among multiple threads comes into picture we need thread synchronization. Let’s take a thread program example in which console will be shared by two threads to print a string on it.
Let’s see the output of the below program where we are not synchronizing the printer() function that is used by two threads.
printer() function print a string i.e. “interview sansar is the excellent resource for interview preparation!!!” on cmd console for each thread.
Look at the Output of below program on console. You should find the unwanted output i.e. mixture of both strings.
Output:
interviewinterview sansar is the excellent resource for interview preparation!!!sansar is the excellent resource for interview preparation!!!
using System;
using System.Threading;// use this namespace for threads
namespace threadsample
{
class Program
{
static void Main(string[] args)
{
//Both thread will print a same string on console.
Thread t1 = new Thread(printer);
Thread t2 = new Thread(printer);
t1.Start();
t2.Start();
}
static void printer()
{
String arr = "interview sansar is the excellent resource for interview preparation!!!";
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
}
}
}
}
With thread synchronization C# example
When we synchronize the code block of printer() function where printing is going on console, program will print the correct string for both threads on the console.
Output:
interview sansar is the excellent resource for interview preparation!!!interview sansar is the excellent resource for interview preparation!!!
In below program we have used Object lock to synchronize the code block in printer () function where threads are printing strings on same cmd console.
using System;
using System.Threading;// use this namespace for threads
namespace threadsample
{
class Program
{
//Object lock to lock the crtical section/ shared resource.
//cmd console is the shared resource here.
private static Object lockCode = new Object();
static void Main(string[] args)
{
//Both thread will print a same string on console.
Thread t1 = new Thread(printer);
Thread t2 = new Thread(printer);
t1.Start();
t2.Start();
}
static void printer()
{
String arr = "interview sansar is the excellent resource for interview preparation!!!";
//Synchronize the code for printing string on console.
lock (lockCode)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
}
}
}
}
}