Avoid deadlocks in a multi-threaded process

What are the best practices / idioms if someone follows in order to avoid deadlocks?

+4
source share
6 answers

Four conditions that must occur for a dead end:

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

  • Hold and wait: processes that already contain resources may request new resources

  • The lack of continuity conditions: no resource can be forcibly removed from the process containing it, resources can only be released by an explicit process action

  • The condition for cyclic waiting: two or more processes form a circular chain in which each process expects a resource, which the next process in the chain contains

Avoid at least one of them, and preferably more, and you should not have too many problems.

+6
source

The canonical method of preventing deadlocks is to have a locking hierarchy. Ensure that all threads receive locks or other resources in the same order. This avoids the deadlock scenario where thread 1 holds lock A and requires lock B, while thread 2 holds lock B and requires lock A. With the lock hierarchy, both threads would get locks in the same order (for example, A to B)

+1
source

There is a so-called Banker algorithm to prevent deadlocks. You might also consider using Watch Dog to break the deadlock. There are also some interesting points.

+1
source

It would be best practice to define a class for your thread and use only non-static fields of that class in your thread so that your threads do not share memory.
Of course, to avoid deadlocks, you could also avoid using semaphores, critical sections, and mutexes. Less if you want to avoid dead ends. Unfortunately, they are required if any memory or other resource is shared between two threads or you risk data corruption.

0
source

Among the various ways to enter critical sections, semaphores and mutexes are the most popular.

  • A semaphore is a waiting mechanism, and a mutex is a blocking mechanism, well, the concept as a whole is confusing, but, in short, a thread that activates a mutex can deactivate it. with that in mind ...

  • Do not allow any process to block a partial amount of resources, if the process requires 5 resources, wait until all of them are available.

  • If you use the semaphore here, you can unlock / disable the resource occupied by another thread. by this I mean that prevention is another reason.

These 2 are basic conditions for me, the remaining 2 of the 4 general precautions may be associated with them.

If you do not agree with ps, add comments. I already finished gtg, later I will add a cleaner and more clear explanation.

-1
source

Source: https://habr.com/ru/post/1286751/


All Articles