A picture to fully understand the locking mechanism of MySQL

Locks are a very important part of MySQL, and locks have a decisive impact on the concurrency of MySQL data access. There is also a lot of knowledge involved in locks, so if you want to finish it and digest it in your stomach, you need to calm down and savor it over and over again. This article is a general arrangement of locks, and some related in-depth details still need to find relevant books to continue to consolidate.

A picture to fully understand the locking mechanism of MySQL

Knowledge of locks

1.1 Interpretation of locks

计算机协调多个进程或线程并发访问某一资源的机制。

1.2 The importance of locks

在数据库中,除传统计算资源(CPURAMI\O等)的争抢,数据也是一种供多用户共享的资源。
如何保证数据并发访问的一致性,有效性,是所有数据库必须要解决的问题。
锁冲突也是影响数据库并发访问性能的一个重要因素,因此锁对数据库尤其重要。

1.3 Disadvantages of locks

加锁是消耗资源的,锁的各种操作,包括获得锁、检测锁是否已解除、释放锁等 ,都会增加系统的开销。

1.4 Simple example

现如今网购已经特别普遍了,比如淘宝双十一活动,当天的人流量是千万及亿级别的,但商家的库存是有限的。
系统为了保证商家的商品库存不发生超卖现象,会对商品的库存进行锁控制。当有用户正在下单某款商品最后一件时,
系统会立马对该件商品进行锁定,防止其他用户也重复下单,直到支付动作完成才会释放(支付成功则立即减库存售罄,支付失败则立即释放)。

type of lock

2.1 Table lock

type

读锁(read lock),也叫共享锁(shared lock)
针对同一份数据,多个读操作可以同时进行而不会互相影响(select)
写锁(write lock),也叫排他锁(exclusive lock)
当前操作没完成之前,会阻塞其它读和写操作(update、insert、delete)

storage engine default lock

MyISAM

features

1. 对整张表加锁
2. 开销小
3. 加锁快
4. 无死锁
5. 锁粒度大,发生锁冲突概率大,并发性低

in conclusion

1. 读锁会阻塞写操作,不会阻塞读操作
2. 写锁会阻塞读和写操作

suggestion

MyISAM的读写锁调度是写优先,这也是MyISAM不适合做写为主表的引擎,因为写锁以后,其它线程不能做任何操作,大量的更新使查询很难得到锁,从而造成永远阻塞。

2.2 row lock

type

读锁(read lock),也叫共享锁(shared lock)
允许一个事务去读一行,阻止其他事务获得相同数据集的排他锁
写锁(write lock),也叫排他锁(exclusive lock)
允许获得排他锁的事务更新数据,阻止其他事务取得相同数据集的共享锁和排他锁
意向共享锁(IS
一个事务给一个数据行加共享锁时,必须先获得表的IS
意向排它锁(IX
一个事务给一个数据行加排他锁时,必须先获得该表的IX

storage engine default lock

InnoDB

features

1. 对一行数据加锁
2. 开销大
3. 加锁慢
4. 会出现死锁
5. 锁粒度小,发生锁冲突概率最低,并发性高

Problems caused by transaction concurrency

1. 更新丢失
解决:让事务变成串行操作,而不是并发的操作,即对每个事务开始---对读取记录加排他锁
2. 脏读
解决:隔离级别为Read uncommitted
3. 不可重读
解决:使用Next-Key Lock算法来避免
4. 幻读
解决:间隙锁(Gap Lock)

2.3 Page Lock

开销、加锁时间和锁粒度介于表锁和行锁之间,会出现死锁,并发处理能力一般(此锁不做多介绍)

How to lock it?

3.1 Table lock

Implicit locking (default, automatic locking and automatic release)

select //上读锁
insert、update、delete //上写锁

Explicit locking (manual)

lock table tableName read;//读锁
lock table tableName write;//写锁

unlock (manual)

unlock tables;//所有锁表
session01 session02
lock table teacher read;// read lock
select * from teacher; // can be read normally select * from teacher;// can be read normally
update teacher set name = 3 where id =2;// An error cannot be written due to the read lock update teacher set name = 3 where id =2;// blocked
unlock tables;//unlock
update teacher set name = 3 where id =2;//The update operation is successful
session01 session02
lock table teacher write;// write lock
select * from teacher; // can be read normally select * from teacher;// blocked
update teacher set name = 3 where id =2;// can update normally update teacher set name = 4 where id =2;// blocked
unlock tables;//unlock
select * from teacher;// read successfully
update teacher set name = 4 where id =2;//The update operation is successful

3.2 row lock

Implicit locking (default, automatic locking and automatic release)

select //不会上锁
insert、update、delete //上写锁

Explicit locking (manual)

select * from tableName lock in share mode;//读锁
select * from tableName for update;//写锁

unlock (manual)

1. 提交事务(commit)
2. 回滚事务(rollback)
3. kill 阻塞进程
session01 session02
begin;
select * from teacher where id = 2 lock in share mode;// 上读锁
select * from teacher where id = 2;// can be read normally
update teacher set name = 3 where id =2;// can update the operation update teacher set name = 5 where id =2;// blocked
commit;
update teacher set name = 5 where id =2;//The update operation is successful
session01 session02
begin;
select * from teacher where id = 2 for update;//
select * from teacher where id = 2;// can be read normally
update teacher set name = 3 where id =2;// can update the operation update teacher set name = 5 where id =2;// blocked
rollback;
update teacher set name = 5 where id =2;//The update operation is successful
为什么上了写锁,别的事务还可以读操作?
因为InnoDB有MVCC机制(多版本并发控制),可以使用快照读,而不会被阻塞。

Implementation Algorithm of Row Lock

4.1 Record Lock lock

单个行记录上的锁
Record Lock总是会去锁住索引记录,如果InnoDB存储引擎表建立的时候没有设置任何一个索引,这时InnoDB存储引擎会使用隐式的主键来进行锁定

4.2 Gap Lock Lock

当我们用范围条件而不是相等条件检索数据,并请求共享或排他锁时,InnoDB会给符合条件的已有数据记录的索引加锁,对于键值在条件范围内但并不存在的记录。

优点:解决了事务并发的幻读问题
不足:因为query执行过程中通过范围查找的话,他会锁定争个范围内所有的索引键值,即使这个键值并不存在。
间隙锁有一个致命的弱点,就是当锁定一个范围键值之后,即使某些不存在的键值也会被无辜的锁定,而造成锁定的时候无法插入锁定键值范围内任何数据。在某些场景下这可能会对性能造成很大的危害。

4.3 Next-key Lock Lock

同时锁住数据+间隙锁
在Repeatable Read隔离级别下,Next-key Lock 算法是默认的行记录锁定算法。

4.4 Notes on row locks

1. 只有通过索引条件检索数据时,InnoDB才会使用行级锁,否则会使用表级锁(索引失效,行锁变表锁)
2. 即使是访问不同行的记录,如果使用的是相同的索引键,会发生锁冲突
3. 如果数据表建有多个索引时,可以通过不同的索引锁定不同的行

How to troubleshoot locks?

5.1 Table lock

View table lock status

show open tables;

A picture to fully understand the locking mechanism of MySQL

Table lock analysis

show status like 'table%';

A picture to fully understand the locking mechanism of MySQL

1. table_locks_waited
出现表级锁定争用而发生等待的次数(不能立即获取锁的次数,每等待一次值加1),此值高说明存在着较严重的表级锁争用情况
2. table_locks_immediate
产生表级锁定次数,不是可以立即获取锁的查询次数,每立即获取锁加1

5.2 Row locks

Row Lock Analysis

show status like 'innodb_row_lock%';

A picture to fully understand the locking mechanism of MySQL

1. innodb_row_lock_current_waits //当前正在等待锁定的数量
2. innodb_row_lock_time //从系统启动到现在锁定总时间长度
3. innodb_row_lock_time_avg //每次等待所花平均时间
4. innodb_row_lock_time_max //从系统启动到现在等待最长的一次所花时间
5. innodb_row_lock_waits //系统启动后到现在总共等待的次数

information_schema library

1. innodb_lock_waits表
2. innodb_locks表
3. innodb_trx表

optimization suggestion

1. 尽可能让所有数据检索都通过索引来完成,避免无索引行锁升级为表锁
2. 合理设计索引,尽量缩小锁的范围
3. 尽可能较少检索条件,避免间隙锁
4. 尽量控制事务大小,减少锁定资源量和时间长度
5. 尽可能低级别事务隔离

deadlock

6.1 Explanation

指两个或者多个事务在同一资源上相互占用,并请求锁定对方占用的资源,从而导致恶性循环的现象

6.2 Conditions for generation

1. 互斥条件:一个资源每次只能被一个进程使用
2. 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
3. 不剥夺条件:进程已获得的资源,在没有使用完之前,不能强行剥夺
4. 循环等待条件:多个进程之间形成的一种互相循环等待的资源的关系

6.1 Resolution

1. 查看死锁:show engine innodb status \G
2. 自动检测机制,超时自动回滚代价较小的事务(innodb_lock_wait_timeout 默认50s)
3. 人为解决,kill阻塞进程(show processlist)
4. wait for graph 等待图(主动检测)

6.1 How to avoid

1. 加锁顺序一致,尽可能一次性锁定所需的数据行
2. 尽量基于primary(主键)或unique key更新数据
3. 单次操作数据量不宜过多,涉及表尽量少
4. 减少表上索引,减少锁定资源
5. 尽量使用较低的隔离级别
6. 尽量使用相同条件访问数据,这样可以避免间隙锁对并发的插入影响
7. 精心设计索引,尽量使用索引访问数据
8. 借助相关工具:pt-deadlock-logger

Optimistic locking and pessimistic locking

A picture to fully understand the locking mechanism of MySQL

7.1 Pessimistic locking

explain

假定会发生并发冲突,屏蔽一切可能违反数据完整性的操作

Implementation Mechanism

表锁、行锁等

implementation level

数据库本身

Applicable scene

并发量大

7.2 Optimistic locking

explain

假设不会发生并发冲突,只在提交操作时检查是否违反数据完整性

Implementation Mechanism

提交更新时检查版本号或者时间戳是否符合

implementation level

业务代码

Applicable scene

并发量小

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/131736796
Recommended