为什么检测到此代码中的死锁?

时间:2015-11-19 01:09:36

标签: mysql deadlock

我学会了共享锁,它可以阻止exlcusive锁。当执行带有外键的insert语句时,父记录将被共享锁定。 但是在下面的代码中,slock似乎并没有阻止xlock。那为什么会出现死锁?

#!/usr/bin/env zsh
mysql -u root test <<EOS
drop table if exists child;
create table child (id int, pid int, primary key (id, pid))engine=innodb;

drop table if exists parent;
create table parent (id int, count int, primary key (id))engine=innodb;
insert into parent values (1, 0);

alter table child add foreign key (pid) references parent (id);
EOS

q1=$(cat<<EOS
begin;
insert into child values (1, 1);  -- slock parent(id=1)
select sleep(1);
update parent set count = count + 1 where id = 1;  -- xlock(parent(id=1))
commit;
EOS
)

q2=$(<<EOS
begin;
update parent set count = count + 1 where id = 1;  -- xlock(parent(id=1))
select sleep(1);
commit;
EOS
)

mysql -u root test <<< "$q1" &
mysql -u root test <<< "$q2" &
wait
mysql -u root test -e 'select * from child;'
mysql -u root test -e 'select * from parent;

0 个答案:

没有答案