Thread 1 locked on Resources 1 and tries to acquire a lock on Reosurce 2.
At the same time, Thread 2 has a lock on Resource 2 and it tries to acquire lock on Resource 1.
Two threads never give up their locks, hence a DEADLOCK occures.
Solution :
The simplest way to avoid deadlock is to use a timeout value .
You can use the Monitor class (system.Threading.Monitor) to set a timeout during acquiring a lock.
Ex. in C#
if(Monitor.TryEnter(this, 500))
{
// critical section
}
catch (Exceprion ex)
{
}
finally
{
Monitor.Exit();
}
Here the timeout is 500 milliseconds .
If the lock can't be acquired, after 500 miliseconds, timeout occurs and the code exit the Monitor block.