当两个(或更多)事务各自持有另一个需要的锁时,就会发生死锁,因此双方都无法继续进行——它们陷入相互等待的僵局。数据库检测死锁并通过中止一个事务("victim")来解决它,该事务必须重试。理解原因和预防对于并发应用至关重要。
死锁如何发生
text
Transaction A: locks row 1, then wants row 2
Transaction B: locks row 2, then wants row 1
→ A waits for B (to release row 2), B waits for A (to release row 1) → DEADLOCK
Neither can proceed; they're waiting on each other in a cycle.
sql
; ;
accounts .. id; accounts .. id;
accounts .. id; accounts .. id;
