解释mysql中的死锁

cs7cruho  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(285)

我是mysql的新手。我遇到了僵局。请帮忙解释一下。
我创建了一个表:

create table test(id INT, value INT, PRIMARY KEY(id));
insert into test(id, value) values(0, 0);
insert into test(id, value) values(1, 1);

在事务1中:

begin;
select * from test where id=1 for update; //it holds record_lock(id=1)

在事务2中:

begin;
select * from test where id=1 for update; //it waits for record_lock(id=1)

然后在事务1中:

select * from test where id>0 for update;

在事务1中的此语句之后,事务2出现错误: ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction 这是最近检测到的死锁:

r1zk6ea1

r1zk6ea11#

在阅读了mysql的这个例子之后,我知道了原因:
1) 事务处理01(t1):

begin;
select * from test where id=1 for update; //it holds record_lock(id=1)

执行该语句后,t1持有记录锁(id=1)
2) 事务处理02(t2):

begin;
select * from test where id=1 for update; //it waits for record_lock(id=1)

t2被放入等待队列,因为它试图获取t1持有的锁。
3) 事务处理01:

select * from test where id>0 for update;`enter code here`

此语句试图获取间隙锁(从1到无穷大),但t2正在队列中等待记录锁(id=1),因此它应该等待t2。死锁发生。即使t1有记录锁(id=1),它也无法获得这个间隙锁,因为t2正在队列中等待。

相关问题