mysql的锁机制
行锁和表锁
表级锁:开销小,加锁快;不会出现死锁;锁定粒度大,发生锁冲突的概率最高,并发度最低。
行级锁:开销小,加锁慢;会出现死锁;锁定粒度最小,发生锁冲突的概率最低,并发度也最高。
行锁,走索引的时候会用到行锁。
select * from test where id = 3 for update
update test set age= 3 where id = 3
不走索引的时候会用到表锁
select * from test where age= 3
死锁
互相争夺资源,没有外力推动循环等待。
事务A:
begin;
select * from test where id = 2 for update
执行成功
事务B:
begin;
select * from test where id = 3 for update
执行成功
事务A:
select * from test where id = 3 for update
等待
事务B:
select * from test where id = 2 for update
[Err] 1213 - Deadlock found when trying to get lock; try restarting transaction
读写锁
读锁:select * from test where id = 2 lock in share mode
读锁又叫共享锁,其他事务也可以获取读锁,但是不能写
写锁:update、insert、delete 、select ....for update
写锁又叫排他锁,其他事务不能获取该锁。
select不加锁的话是与锁无关的。他遵守的是MVCC机制。
间隙锁:
参考链接 https://blog.csdn.net/hjxisking/article/details/107017190
浙公网安备 33010602011771号