为什么以不同的顺序解锁两个锁定的银行账户会导致死锁?

Why would unlocking two locked bank accounts in a different order result in a deadlock?

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.

例子:从A账户取款,存入B账户。

所以,我会先锁A,再锁B,那如果先解锁B,再解锁A,为什么会死锁?

请说明。

因为可以满足以下顺序:

  • 线程 1 锁定 A.
  • 线程2锁住B.
  • 线程 1 尝试锁定 B 并阻塞。
  • 线程 2 尝试锁定 A 并阻塞。

两个线程都在等待对方,所以你有一个死锁。

为避免这种情况,您必须始终以相同的顺序获取锁。解锁顺序无关紧要