前言:出于兴趣,特地模拟了一下mysql死锁的产生的场景。
一、环境准备
在test数据库下面创建一个表t1
mysql> CREATE TABLE t1 ( -> a int(11) NOT NULL DEFAULT '0', -> PRIMARY KEY (a) -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ; Query OK, 0 rows affected (0.02 sec) |
二、往表中插入数据
mysql> insert into t1 values(1); Query OK, 1 row affected (0.00 sec) mysql> insert into t1 values(2); Query OK, 1 row affected (0.00 sec) mysql> insert into t1 values(3); Query OK, 1 row affected (0.00 sec) mysql> commit; Query OK, 0 rows affected (0.01 sec) mysql> select * from t1; +---+ | a | +---+ | 1 | | 2 | | 3 | +---+ 3 rows in set (0.00 sec) |
三、开始演示
session 1 |
session 2 |
set autocommit=0; mysql> select * from t1 where a=1 for update; +---+ | a | +---+ | 1 | +---+ 1 row in set (0.00 sec) //对行1加锁 |
|
set autocommit=0; mysql> select * from t1 where a=2 for update; +---+ | a | +---+ | 2 | +---+ 1 row in set (0.01 sec) //对行2加锁 |
|
mysql> select * from t1 where a=2 for update; //当前状态处于锁等待状态,等待session2释放锁; |
|
mysql> select * from t1 where a=1 for update; //等待session1释放锁 ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction 当前session 2被回滚了 |
这样session1和session2就处于相持的状态;mysql检测到两个session互为等待的情况下就会把最后一个session做了回滚操作;
总结:如果想要看更详细的锁状态,可以查看这三张表INNODB_TRX、INNODB_LOCKS、INNODB_LOCK_WAITS,上面的文档还记录着,这里偷懒一下。
.......................................................................................................................................................................
本文作者:JOHN,某上市公司DBA,业余时间专注于数据库的技术管理,从管理的角度去运用技术。
ORACLE技术博客:ORACLE 猎人笔记 数据库技术群:367875324 (请备注ORACLE管理 )
........................................................................................................................................................................