欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL死锁

程序员文章站 2023-03-26 18:14:32
https://dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks.html 什么是mysql的死锁? A deadlock is a situation where different transactions are unable to procee ......

什么是mysql的死锁?

a deadlock is a situation where different transactions are unable to proceed because each holds a lock that the other needs. because both transactions are waiting for a resource to become available, neither ever release the locks it holds. 

简单来说可以提炼出2个词:环路等待(each holds a lock that the other needs)和不可剥夺(neither ever release the locks it holds)。

其实广泛意义上死锁的四个必要条件也可以直接简化为上述两个条件,剩下的互斥和请求保持条件只是两个众所周知的补充。

一、一个简单的死锁示例:

会话a:

mysql> create table t (i int) engine = innodb;
query ok, 0 rows affected (1.07 sec)

mysql> insert into t (i) values(1);
query ok, 1 row affected (0.09 sec)

mysql> start transaction;
query ok, 0 rows affected (0.00 sec)

mysql> select * from t where i = 1 lock in share mode;
+------+
| i    |
+------+
| 1    |
+------+

会话b:

mysql> start transaction;
query ok, 0 rows affected (0.00 sec)

mysql> delete from t where i = 1;

此时会话b会被阻塞(直到锁请求超时)。

此时会话a继续执行:
delete from t where i = 1;

会话b会被立马rollback,因为产生了死锁,最近的死锁信息可以通过show engine innodb status\g看到。

打开innodb_print_all_deadlocks参数之后,死锁信息还会在error日志里打印。鉴于本例过于简单就不占用篇幅分析死锁信息了。

set @@global.innodb_print_all_deadlocks=on;

innodb会选择耗费资源较少的事务进行回滚(取决于dml涉及的行数和size)。

二、一个实际的死锁示例:

error日志里显示的死锁日志为:

innodb: transactions deadlock detected, dumping detailed information.
*** (1) transaction:
transaction 209262583957, active 1 sec starting index read
mysql tables in use 2, locked 2
lock wait 4 lock struct(s), heap size 1184, 2 row lock(s)
mysql thread id 129183854, os thread handle 0x7f1aeae7a700, query id 68320628504 <服务器a信息> updating
update  tb_authorize_info set account_balance=account_balance-  100.00 
     where (select a.account_balance from 
(select account_balance from tb_authorize_info a where appid =  '49e5bd695f853dc3' )a)  -  100.00 > 0 
 and appid = '49e5bd695f853dc3'
*** (1) waiting for this lock to be granted:
record locks space id 1845 page no 4 n bits 96 index `primary` of table `xxx`.`tb_authorize_info` trx id 209262583957 lock_mode x locks rec but not gap waiting
record lock, heap no 18 physical record: n_fields 32; compact format; info bits 0
......

*** (2) transaction:
transaction 209262584968, active 1 sec starting index read
mysql tables in use 2, locked 2
4 lock struct(s), heap size 1184, 2 row lock(s)
mysql thread id 129183879, os thread handle 0x7f198b208700, query id 68320632234 <服务器b信息> updating
update  tb_authorize_info set account_balance=account_balance-  100.00 
     where (select a.account_balance from 
(select account_balance from tb_authorize_info a where appid =  '49e5bd695f853dc3' )a)  -  100.00 > 0 
 and appid = '49e5bd695f853dc3'
*** (2) holds the lock(s):
record locks space id 1845 page no 4 n bits 96 index `primary` of table `xxx`.`tb_authorize_info` trx id 209262584968 lock mode s locks rec but not gap
record lock, heap no 18 physical record: n_fields 32; compact format; info bits 0
......

*** (2) waiting for this lock to be granted:
record locks space id 1845 page no 4 n bits 96 index `primary` of table `xxx`.`tb_authorize_info` trx id 209262584968 lock_mode x locks rec but not gap waiting
record lock, heap no 18 physical record: n_fields 32; compact format; info bits 0
......

*** we roll back transaction (2)

这个死锁属于简单的死锁,由于网络或其他延迟导致应用请求发送到了2台负载均衡的应用服务器,两个应用程序同时请求数据库执行sql,两者都根据where条件先获取到了s锁,然后准备升级为x锁以便更新,但是各自被对方的s锁阻塞,因此形成死锁,不过死锁很快被mysql杀掉,事务1正常执行完毕,事务二回滚,前台业务除了一点点延迟基本没啥影响。

三、*上另一个死锁:

有人在*上发了一个死锁的信息,尝试直接解析此类信息对分析高并发下的sql卡慢会有帮助因此尝试自己解析,由于时间久远现在我已经找不到相关链接也懒得去找了。

latest detected deadlock
------------------------
130409  0:40:58
*** (1) transaction:
transaction 3d61d41f, active 3 sec inserting
mysql tables in use 1, locked 1
lock wait 43 lock struct(s), heap size 6960, 358 row lock(s), undo log entries 43
mysql thread id 17241690, os thread handle 0x7ffd3469a700, query id 860259163 localhost root update
#############
insert into `notification` (`other_grouped_notifications_count`, `user_id`, `notifiable_type`, `action_item`, `action_id`, `created_at`, `status`, `updated_at`) 
values (0, 4442, 'match', 'match', 224716, 1365448255, 1, 1365448255)
#############
*** (1) waiting for this lock to be granted:
record locks space id 0 page no 272207 n bits 1272 index `user_id` of table `notification` trx id 3d61d41f lock_mode x locks gap before rec insert intention waiting
record lock, heap no 69 physical record: n_fields 2; compact format; info bits 0
 0: len 4; hex 8000115b; asc    [;;
 1: len 4; hex 0005e0bb; asc     ;;
-- 事务1欲插入数据user_id=4442,因此首先获取了对应主键(lower_bound,4443]范围上的插入意向锁,然后想要在辅助索引(lower_bound,4443]的范围上加insert intention lock,但被阻塞,推断这个范围上已经有了其他事务的行锁
-- 事务1需要获取2个插入意向锁后才会开始插入操作,这两个锁的获取是不可分割的
*** (2) transaction:
transaction 3d61c472, active 15 sec starting index read
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1248, 2 row lock(s)
mysql thread id 17266704, os thread handle 0x7ffd34b01700, query id 860250374 localhost root updating
#############
update `notification` set `status`=0 where user_id = 4443 and status=1
#############
*** (2) holds the lock(s):
-- 事务2的update语句要更新user_id=4443的记录,因此首先在user_id索引的(lower_bound,4443]范围添加了x模式的next-key行锁,事务1就是被这个next-key行锁阻塞的
record locks space id 0 page no 272207 n bits 1272 index `user_id` of table `notification` trx id 3d61c472 lock_mode x
record lock, heap no 69 physical record: n_fields 2; compact format; info bits 0
 0: len 4; hex 8000115b; asc    [;;
 1: len 4; hex 0005e0bb; asc     ;;
*** (2) waiting for this lock to be granted:
-- 当事务2尝试更新主键数据时要获取user_id=4443对应主键的行锁,但是发现主键的(lower_bound,4443]范围上已经被事务1加了insert intention lock,因此被阻塞
-- 同样事务2获取辅助索引的next-key和主键的record锁也是不可分割的,只有都获取完毕才能进行update
record locks space id 0 page no 261029 n bits 248 index `primary` of table `notification` trx id 3d61c472 lock_mode x locks rec but not gap waiting
record lock, heap no 161 physical record: n_fields 16; compact format; info bits 0
 0: len 4; hex 0005e0bb; asc     ;;
 1: len 6; hex 00000c75178f; asc    u  ;;
 2: len 7; hex 480007c00c1d10; asc h      ;;
 3: len 4; hex 8000115b; asc    [;;
 4: len 8; hex 5245474953544552; asc register;;
 5: sql null;
 6: sql null;
 7: sql null;
 8: len 4; hex d117dd91; asc     ;;
 9: len 4; hex d117dd91; asc     ;;
 10: len 1; hex 80; asc  ;;
 11: sql null;
 12: sql null;
 13: sql null;
 14: sql null;
 15: len 4; hex 80000000; asc     ;;

*** we roll back transaction (2)

所以这个死锁的出现就很容易理解了,事务1先获取了4442位置主键的插入意向锁,在获取辅助索引上的插入意向锁时被事务2 update语句的next-key行锁阻塞导致插入意向锁获取失败,而事务2的update获取了索引的next-key行锁后尝试更新主键(即在主键上加非gap行锁)却被事务1的插入意向锁阻塞。

两个事务都不能放弃自己已有的资源,都请求与对方不兼容的锁,不可剥夺且形成环路等待因此死锁。
这个死锁的根源就在于事务2的update语句持续的时间过长,导致后继insert语句卡死。

四、如何避免死锁?

其实官网有一篇完整的介绍:

但是内容有点多,我还是习惯用几句话总结下:

1、尽可能优化sql的查询性能使得事务尽可能的短小。

2、如果不介意幻读可以使用read committed隔离级别以禁止范围锁。

3、如果前两者都做不到或者sql优化的空间比较小,那么尽量分表分库,通过增加资源(或者叫分散资源)减少资源冲突的几率。

五、总结:

由于mysql innodb特殊的行锁机制,死锁通常都是涉及到插入意向锁和next-key锁的,因为这两个锁是范围锁,范围锁涉及的目的就是为避免幻读,这会锁定一些自己不需要操作的记录。

不过在mysql中死锁从来都不是大问题,死锁通常都是数据库卡慢的果,而非因。而且由于数据库中普遍存在的死锁查杀机制,死锁产生后会很快被查杀。

真正可能引发数据库性能问题的,是高并发下的长事务,这种事务会导致undo等资源的争用,会占用binlog的提交队列导致后继事务处于commit阶段无法提交,即便强制kill也会引发长时间的rollback操作。

因此高并发下的长事务和低性能sql才是死锁的主因,因为他们慢且作为一个整体在完成之前不会释放资源产生环路等待。