The Problem "Concurrency"When you build multithreaded application, your program needs to ensure that shared data should be protected from against the possibility of multiple threads engagement with its value. What's going to happen if multiple threads were accessing the data at the same point? CLR can suspend your any thread for a while who's going to update the value or is in the middle of updating the value and same time a thread comes to read that value which is not completely updated, that thread is reading an uncompleted/unstable data. To illustrate the problem of concurrency let write some line of codeclass Program
{
static void Main(string[] args)
{
Console.WriteLine("----Synchronnization of Threads-----");
Console.WriteLine("Main Thread {0}", Thread.CurrentThread.ManagedThreadId);
Printer p = new Printer(); Thread[] threads = new Thread[5]; //Queue 5 threads
for (int i = 0; i < 5; i++)
{
threads[i] = new Thread(new ThreadStart(p.PrintNumbersNonSync));
}
foreach (Thread t in threads)
{
t.Start();
} Console.ReadLine();
}
}class Printer
{
public void PrintNumbersNonSync()
{
Console.WriteLine(" ");
Console.WriteLine("Executing Thread {0}", Thread.CurrentThread.ManagedThreadId);
for (int i = 1; i <= 10; i++)
{
Console.Write(i + " ");
}
}
}
Read more: C# Corner
QR:
{
static void Main(string[] args)
{
Console.WriteLine("----Synchronnization of Threads-----");
Console.WriteLine("Main Thread {0}", Thread.CurrentThread.ManagedThreadId);
Printer p = new Printer(); Thread[] threads = new Thread[5]; //Queue 5 threads
for (int i = 0; i < 5; i++)
{
threads[i] = new Thread(new ThreadStart(p.PrintNumbersNonSync));
}
foreach (Thread t in threads)
{
t.Start();
} Console.ReadLine();
}
}class Printer
{
public void PrintNumbersNonSync()
{
Console.WriteLine(" ");
Console.WriteLine("Executing Thread {0}", Thread.CurrentThread.ManagedThreadId);
for (int i = 1; i <= 10; i++)
{
Console.Write(i + " ");
}
}
}
Read more: C# Corner
QR: