How to avoid Dead lock | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 2

How to avoid Dead lock

Hi Every one talks about two threads blocking mutex in different order as below: Thread 1 : lock M1 and then M2 Thread 2 : lock M2 and then M1 This may result into dead lock and solution is to follow either lock M1 then lock M2 or lock M2 then lock M1 for both the threads If so, we are not unnecessarily locking the operations ? There is something time consuming events happening in thread 2 between lock of M2 and M1 Just to avoid Dead lock , we are blocking first M1 and then M2 even if we need only lock on M2 to do some time consuming calculations or work Isn't it reducing parellelism to avoid Dead lock? Any better or alternate solutions?

19th Mar 2022, 7:25 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 ответов
+ 2
I am only stating the obvious that processes should not hold onto shared resources any longer than is absolutely minimally necessary. Do as much processing as safely possible outside of any mutex locks. Then lock just long enough to update (or whatever) then get back out instantly. Avoid holding more than one lock, but if you truly must, then prepare a contingency to let go of all locks and start completely over if one of them cannot be allocated within a reasonable time period.
19th Mar 2022, 5:31 PM
Brian
Brian - avatar
+ 3
If you only need the M2 resource, then only lock the M2 resource and leave M1 alone. If you need both, then agree in advance on the order they will be locked. If you are going to do something with one of the locks for a long time before needing the second one, then lock the first resource, work with it, then unlock it; then lock both for the next part of your task. Only hold a lock when you actually need it, and never hold a lock longer than necessary. If you’re holding on to locks for long periods, you need to rethink how you’re using the resources. If your threads are holding a lock for so long that there is notable contension then you're program is probably mal-formed. In general, a mutex should be held for as short time as possible to protect shared data. Nested locking is a well established good practice to avoid deadlocks
20th Mar 2022, 2:53 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Interesting question. Not sure I can add any ideas, but to reinforce the idea of not tying up resources! If your thread would hold M1 for more than a couple milliseconds then maybe it is time to review its design. And if it is unable to acquire M2 after some quick retries it should release M1 and start over.
19th Mar 2022, 11:08 AM
Brian
Brian - avatar
0
Sorry I am relatively less experienced on the thread. Could you please elaborate if possible?
19th Mar 2022, 12:30 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thanks ..got it now
19th Mar 2022, 7:33 PM
Ketan Lalcheta
Ketan Lalcheta - avatar