views:

757

answers:

6

When using multiple threads, shared memory needs to be locked by critical sections. However, using critical sections causes potential deadlocks. How can they be avoided?

+1  A: 

One way is to use a hierarchy of critical sections. If you ensure that a parent critical section is never entered within one of its children. The difficulty is to enforce this hierarchy.

Dimitri C.
A: 

You must code multi-thread programs very carefully. There's no short-cut, you must understand the flow of your program, otherwise you'll be doomed.

felipec
+2  A: 

When I work in C++, the following works for me:

  1. all public methods (excluding ctor and dtor) of a threadsafe class lock

  2. private methods cannot call public methods

It's not a general deadlock avoidance method.

Rhythmic Fistman
+3  A: 

The Related list to the right on this page contains a few links that provides interesting information on the topic.

In addition to that list, there are many other SO questions discussing the topic, such as

...and many more

Fredrik Mörk
Thanks, I'll have a look at those questions.
Dimitri C.
+1  A: 

You can avoid critical sections by using message passing instead (synchronous and asynchronous calls). When using synchronous calls, you still have to make sure not to make a circular call, in which thread A asks thread B a question, and B needs to ask A a question to be able to respond.

Another option is to make asynchronous calls instead. However, it is more difficult to get return values.

Note: Indeed, a message passing system is implemented using a critical section that locks the call queue, but it is abstracted away.

Dimitri C.
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