views:

975

answers:

6

What are the best practices/idioms should someone follow in order to avoid deadlocks?

+6  A: 

Please see What are common reasons for deadlocks?

Mitch Wheat
+1  A: 

The canonical technique for deadlock avoidance is to have a lock hierarchy. Make sure that all threads acquire locks or other resources in the same order. This avoids the deadlock scenario where thread 1 hold lock A and needs lock B while thread 2 holds lock B and needs lock A. With a lock hierarchy, both threads would have to acquire the locks in the same order (say, A before B).

Keith Smith
A: 

There is so called Banker's algorithm, for deadlock avoidance. Also you can consider the use of Watch Dog in order to break out form deadlock. Here also few interesting points.

Artem Barger
A: 

The best practice would be by defining a class for your thread and use only non-static fields from this class in your thread so your threads won't be sharing any memory.
Of course, to avoid deadlocks you could also avoid the use of semaphores, critical sections and mutexes. Less is better, if you want to avoid deadlocks. Unfortunately, these are required if some memory or other resource is shared between two threads or else you risk corruption of data.

Workshop Alex
A: 

There are four conditions which must occur for deadlock to occur:

  1. Mutual exclusion condition: a resource that cannot be used by more than one process at a time

  2. Hold and wait condition: processes already holding resources may request new resources

  3. No preemption condition: No resource can be forcibly removed from a process holding it, resources can be released only by the explicit action of the process

  4. Circular wait condition: two or more processes form a circular chain where each process waits for a resource that the next process in the chain holds

Avoid at least one of these, and preferably more, and you shouldn't have too many problems.

alatkins
A: 

Among the various methods to enter critical sections -- semaphores and mutexs are the most popular.

  • A semaphore is a waiting mechanism and mutex is a locking mechanism, well the concept is confusing to the most, but in short, a thread activating a mutex can only deactivate it. with this in mind...

  • Dont allow any process to lock partial no of resources, if a process need 5 resources, wait until all the are available.

  • if u use semaphore here, u can unblock/un-wait the resource occupied by other thread. by this i mean pre-emption is another reason.

These 2 according to me are the basic conditions, the remaining 2 of the common 4 precautions can be related to these.

If u dont agree ps add comments. I've gtg already late, I will later add a cleaner and clearer explanation.

vks