MySql~ Interview Questions Write an example of transaction deadlock under InnoDB engine

Deadlock

  • The so-called deadlock is the four necessary conditions that must occur in the following
  1. Resource mutual exclusion conditions
  2. Keep and request conditions
  3. Inalienable condition
  4. Loop waiting condition
  • In short, the resources accessed are mutually exclusive, that is to say, they are non-preemptible or consumable resources.
  • Multiple transactions have already occupied resources, and want to obtain other resources, the occupied resources are inalienable, and the resources that you want to access are cycled and waited
  • For example, the following example

Build a table

CREATE TABLE `test1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
  • id primary key index

Client one

--T1时刻
BEGIN;
 
--行级锁 id=1 的记录
select * from test1 where id=1 for update ;
 
--T3时刻
--更新 id=2 的记录
update test1 set id=5 where id=2;

Client Two

--T2时刻
BEGIN;
 
--行级锁 id=2 的记录
select * from test1 where id=2 for update ;
 
--T4时刻
--更新 id=1 的记录
update test1 set id=6 where id=1;
  • operation result
update test1 set id=5 where id=1
> 1213 - Deadlock found when trying to get lock; try restarting transaction
> 时间: 0.002s

analysis

Terminal 1 adds an exclusive lock to the record with id=1 in the test1 table at time T1

Terminal 2 adds an exclusive lock to the record of id=2 in the test1 table at T2

The terminal is going to update the record with id=2 in the test1 table at time T3. At this time, the row record has been added with an exclusive lock, and the update operation cannot be performed. It needs to wait for the lock to be released.

Terminal 2 is going to update the record with id=1 in the test1 table at time T4. At this time, the row record has been added with an exclusive lock, and the update operation cannot be performed. It needs to wait for the lock to be released.

The two transactions wait for each other's exclusive lock to be released, so a deadlock occurs

Guess you like

Origin blog.csdn.net/Shangxingya/article/details/113774808