How to find out deadlock and prevent it in C#

Jasmine picture Jasmine · Mar 12, 2013 · Viewed 28.9k times · Source

I had an interview just 5 minutes back, I didn't answer 3 questions, could someone please help me.

Question:

How to look for deadlock scenarios in Multithreaded application function and prevent it ?

Answer I gave:

I gave definition of deadlock and lock, mutex, monitor, semaphore. He told me, that these are tools, but how to look for a deadlock scenario as because when we use these tools blindly, it costs the performance he said :(

Please help me understand this.

Answer

Gaʀʀʏ picture Gaʀʀʏ · Mar 12, 2013

It sounds like you had problems explaining how deadlocks can occur and how they can be prevented.

A deadlock occurs when each thread (minimum of two) tries to acquire a lock on a resource already locked by another. Thread 1 locked on Resources 1 tries to acquire a lock on Resource 2. At the same time, Thread 2 has a lock on Resource 2 and it tries to acquire a lock on Resource 1. Two threads never give up their locks, hence the deadlock occurs.

The simplest way to avoid deadlock is to use a timeout value. The Monitor class (system.Threading.Monitor) can set a timeout during acquiring a lock.

Example

try{
    if(Monitor.TryEnter(this, 500))
    {
        // critical section
    }
}
catch (Exception ex)
{

}
finally
{
    Monitor.Exit();
}

Read More