Why would unlocking two locked bank accounts in a different order result in a deadlock?
Why would unlocking two locked bank accounts in a different order result in a deadlock?
https://stackoverflow.com/a/51890291/462608
If I modify a bank account without locking it, someone else could try to modify it at the same time. This is a race and the result will be undefined behaviour (usually lost or magically created money).
While transferring money, I am modifying 2 bank accounts. So they both need to be locked.
The problem is that when locking more than one thing, every locker must lock and unlock in the same order, otherwise we get deadlocks.
Example: Withdraw from account A and deposit in account B.
So, I would first lock A and then B. Then if I unlock B and then A, why would it result in a deadlock?
Please explain.
@Shawn I will read what you have pointed towards. I know about deadlocks in producer consumer type problems but not in bank accounts.
– Aquarius_Girl
Sep 13 '18 at 6:26
Er, what you're locking with the mutexes doesn't matter. You could use anything as an example. What matters is how you're doing the locking.
– Shawn
Sep 13 '18 at 6:39
1 Answer
1
Because you can meet the following sequence:
Both threads are waiting for each other, so you have a deadlock.
To avoid this you always have to acquire locks in the same order. Unlocking order does not matter.
I am not sure if there is a duplicate for the question on SO - I failed to fine one, but SO search is PITA to deal with.
– StaceyGirl
Sep 13 '18 at 6:44
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not trying to be mean, but the very first result for duckduckgo'ing "mutex deadlock" has an example and explanation. I'm sure google or bing or any other search engine would be the same...
– Shawn
Sep 13 '18 at 6:20