vote buttons
0
1
beginner
0
intermediate
0
advanced
05-Nov-2014 01:30 UTC
K Bonneau
350

1 Answers

vote buttons
0

Two threads each of them waiting for a resource held by the other thread in such a way that neither can proceed, are said to be in a deadlock. 

Suppose there are two threads, T1 & T2 and two resources R1 & R2.

T1 needs to take a lock on R1 and then on R2

T2 needs to take a lock on R2 and then on R1

Now suppose following sequence of events happen:

1. T1 takes a lock on R1

2. T2 takes a lock on R2

3. T1 wants to take a lock on R2 but cannot as T2 has already taken a lock on R2. So T1 waits.

4. Same with T2. T2 wants to take a lock on R1 but cannot as T1 has already taken a lock on R1. T2 waits.

In the above scenario both T1 and T2 are waiting for each other to release locks. Hence no progress can be made by these threads at all. They are in deadlock.

The above scenario in code (Assume Thread1Func and Thread2Func are running on separate threads)


object resourceLock1 = new object();
object resourceLock2 = new object();
 
public void Thread1Func()
{
  lock (resourceLock1)
  {
    //Some Code
    lock (resourceLock2) // Deadlock can happen here
    {/*some code*/}      
  }
}

public void Thread2Func()
{
  lock (resourceLock2)
  {
    //some code
    lock (resourceLock1) // Deadlock can happen here
    {/*some code*/}
  }
}


05-Nov-2014 01:47 UTC
K Bonneau
350