0

How to avoid dead lock

Hi Refer code below: I do know that dead lock is due to m1 and m2 locked in wrong sequence in both threads. But that is my requirement. Like If I will unnecessary lock m1 first, I will not get parallel execution. Is there any other way to remove dead lock? locking m1 first in both functions is the only solution? https://code.sololearn.com/c3drX3hh0pRg/?ref=app

27th Dec 2022, 12:18 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 ответов
+ 2
A simple rule to avoid deadlock is to not acquire more than one locks at a time and if you do, then make sure you aquire them is same order. I know this is not possible in all of the cases, but in your case I think it can be be done by releasing the first lock before aquiring the second lock, and then try to aquire both locks in same order again ( you may use std::lock () to lock multiple locks without worrying about their sequences ) Here is a possible fix 👇 https://code.sololearn.com/cJjaYUs8AHCE/?ref=app
1st Jan 2023, 2:30 AM
Arsenic
Arsenic - avatar
+ 1
This seems great Arsenic should be fine as std::lock gives us relief of locking sequence... also correct me if i misunderstood below: We just have to lock both m1 and m2 to avoid deadlock be with manual care or through good mechanism of lock. Ultimately there will be performance hit as we need to lock both mutex instead of only required one to avoid dead lock
2nd Jan 2023, 9:35 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta I made an assumption that the only reason why you are not releasing (m1) before locking (m2) is that you need data protected by both of them later in function body. If that's not the case then simply releasing the lock when it's no longer needed would also resolve the issue.
3rd Jan 2023, 3:55 PM
Arsenic
Arsenic - avatar
+ 1
Ketan Lalcheta did you try to run this on a local machine ? I don't think there should be a deadlock in this state, most probably it's sololearn which is terminating your execution due to timeout.
9th Jan 2023, 1:01 AM
Arsenic
Arsenic - avatar
+ 1
Thanks Arsenic ... it works..Also I just commented sleep and it works on sololearn as wel.
9th Jan 2023, 5:06 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Sorry Arsenic .. i missed this response and later came to know about your response.. thanks for your help. No actually. I dont need both mutex. One function need one mutex and later second mutex. While order of mutex need is reversed in other function. No mutex need other mutex I tried to release one before using other. Refer code below : But it still goes to dead lock https://code.sololearn.com/c0ruPksKlG3V/?ref=app
8th Jan 2023, 7:49 PM
Ketan Lalcheta
Ketan Lalcheta - avatar