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.






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






@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)