why there is a deadlock in multithreaded program given below
c#, c#-4.0, multithreading
Solution
Assuming you swallow enough exceptions to even get the code running, it can deadlock when the operations execute in the following order:
t2.Resume() //on t1
t1.Resume() //on t2
t2.Suspend() //on t2
t1.Suspend() //on t1
As a result both threads remain suspended.
This is generally not the way to handle thread synchronization. Personally, I have never had to use `Resume` or `Suspend` on threads.
You should read about synchronization mechanisms in .NET, starting with the `lock` statement. I recommend the free chapters from Albahari's c# in a Nutshell:
Problem
I am new to multi threaded programming What is the reason for dead lock in this approach if one Thread has to print odd numbers from 0 to 1000 and other has to print even numbers? ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication9 { class Program { static int count1; static int count2; static Thread t1, t2; static void MulOf2() { while (count1 < 1000) { Console.Write("Th1" + (2 * count1) + "\n"); count1++; if (t2.IsBackground) { if (!t2.IsAlive) { t2.Resume(); } } t1.Suspend(); } } static void Main(string[] args) { t1 = new Thread(MulOf2); t2 = new Thread(MulOf2Plus1); t1.Start(); t2.Start(); } static void MulOf2Plus1() { while (count2 < 1000) { Console.Write("Th2" + ((2 * count2) + 1) + "\n"); count2++; if (t1.IsBackground) { if (!t1.IsAlive) { t1.Resume(); } } t2.Suspend(); } } } } ``` I modified the code to prevent crashes