Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads and simple Dead lock cure

When dealing with threads (specifically in C++) using mutex locks and semaphores is there a simple rule of thumb to avoid Dead Locks and have nice clean Synchronization?

like image 399
PJT Avatar asked Dec 12 '09 07:12

PJT


2 Answers

A good simple rule of thumb is to always obtain your locks in a consistent predictable order from everywhere in your application. For example, if your resources have names, always lock them in alphabetical order. If they have numeric ids, always lock from lowest to highest. The exact order or criteria is arbitrary. The key is to be consistent. That way you'll never have a deadlock situation. eg.

  1. Thread 1 locks resource A
  2. Thread 2 locks resource B
  3. Thread 1 waits to obtain a lock on B
  4. Thread 2 waits to obtain a lock on A
  5. Deadlock

The above can never happen if you follow the rule of thumb outlined above. For a more detailed discussion, see the Wikipedia entry on the Dining Philosophers problem.

like image 50
Asaph Avatar answered Oct 18 '22 18:10

Asaph


  1. If at all possible, design your code so that you never have to lock more then a single mutex/semaphore at a time.
  2. If that's not possible, make sure to always lock multiple mutex/semaphores in the same order. So if one part of the code locks mutex A and then takes semaphore B, make sure that no other part of the code takes semaphore B and then locks mutex A.
like image 23
R Samuel Klatchko Avatar answered Oct 18 '22 19:10

R Samuel Klatchko