Sign in to follow this  
elizas

A single step solution to avoid Deadlock in Multi-threading

Recommended Posts

n its simplest form, deadlock occurs when each of two (minimun two) threads try to acquire a lock on a resource already locked by another. E.g: Take example of two threads 1. thread 1 2. Thread 2 And two resources 1. Resource 1 2. Resource 2 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. Any suggestions are welcomed. Eliza

Share this post


Link to post
Share on other sites
Or what about when the code in the critical section has to be run otherwise the program will be left in an invalid or unsafe state? It's better to avoid deadlocks entirely rather than try to hack around them with a timeout.

Share this post


Link to post
Share on other sites
Quote:
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.


Resources acquisition from threads is better when done in order.
In your case here, thread2 would have to first free res2 and then wait for thread1 to free res1.
So consider using thread entrancy order rather than timing to avoid most deadlocks.

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this