In a multi-threaded system, if a resource is locked by one thread but it is required by another thread and vice-versa, then system hangs and this leads to a Deadlock situation. It is a common and very famous problem in multiprocessing system, parallel computing, and distributed systems. It is one of the hardest problems in multi-threaded systems. Thread Synchronization may be the cause of Deadlock situations.
The following problems may occur due to Thread Synchronization.
- Deadlock
- Starvation
- Priority Inversion
- Busy Waiting
There might be the situation of deadlock in a four crossing road. So, a traffic light system is used to prevent the deadlock on the road and the traffic police works to avoid the deadlock.
Below is an example of deadlock.
- namespace ThreadCodes
- {
- public class DeadLock
- {
- private static object lockA = new object();
- private static object lockB = new object();
- #region Deadlock Case
- private static void CompleteWork1()
- {
- lock (lockA)
- {
- Console.WriteLine("Trying to Acquire lock on lockB");
- lock (lockB)
- {
- Console.WriteLine("Critical Section of CompleteWork1");
- //Access some shared critical section.
- }
- }
- }
- private static void CompleteWork2()
- {
- lock (lockB)
- {
- Console.WriteLine("Trying to Acquire lock on lockA");
- lock (lockA)
- {
- Console.WriteLine("Critical Section of CompleteWork2");
- //Access some shared critical section.
- }
- }
- }
- public static void ExecuteDeadLockCode()
- {
- Thread thread1 = new Thread(CompleteWork1);
- Thread thread2 = new Thread(CompleteWork2);
- thread1.Start();
- thread2.Start();
- thread1.Join();
- thread2.Join();
- //Below code section will never execute due to deadlock.
- Console.WriteLine("Processing Completed....");
- }
- #endregion
- }
- }
- namespace ThreadCodes
- {
- class Program
- {
- static void Main(string[] args)
- {
- DeadLock.ExecuteDeadLockCode();
- Console.ReadKey();
- }
- }
- }
Join the conversation! Your thoughts help the community grow.