mysql 排它锁,共享锁

前言

讲解基于innodb引擎
每次执行时候请 select @@autocommit 看看是不是等于0。每次执行完记得把两个命行执行后commit掉。
还有人评论共享锁,排它锁在哪里。我是真的无语了。

建立测试表
# 建表
create table user (
    id int auto_increment primary key,
    name varchar(10)
) engine = innodb default charset UTF8MB4;

# 插入测试数据
insert into user (`id`,`name`) values (1,"name_1"),(2,"name_2"),(3,"name_3"),(4,"name_4")
测试前的准备工作

开启两个mysql命令行,执行下面操作。下面的演示中使用了for update,是因为我们要使用当前读,
而不是使用快照读

# 先查看是否自动提交,1为自动提交
select @@autocommit

# 关闭自动提交,对当前命令行有效果
set autocommit = 0

# 每次演示完,进入下一个演示,请记得commit结束
行级锁

innodb默认支持行级锁。加锁是对索引加锁,如果不走索引,则退化成表锁

表锁演示
# 命令行1先执行,返回结果
# name 上没索引,造成锁表
select * from user where name = 'name_1' for update;

# 命令行2执行,等待
# 只有等命令行1的commit后才会执行
select * from user where id = 2 for update;
行级锁演示
# 命令行1
select * from user where id = 1 for update;
# 命令行2,ok
select * from user where id = 2 for update;
共享锁

使用 lock in share mode 加锁
多个事务共用一把锁,可以获取数据内容,但不能修改(需要先加锁的释放掉才能修改)

# 命令行1,commit 后命令行2才可修改成功
select * from user where id = 1 lock in share mode;
# 命令行2
select * from user where id = 1 lock in share mode;
update user set name = "name_2_new" where id = 1;
commit;
排它锁

使用 for update 加锁
只有当前事务才能进行读取和修改操作

# 命令行1
select * from user where id = 1 for update;
# 命令行2,要等待1commit
select * from user where id = 1 for update;
# 命令行1
select * from user where id = 1 for update;
# 命令行2,要等待1commit
update user set name = "new_name" where id = 1;
死锁

事务都在等待对方释放资源

# 1⃣️ 命令行1,先执行
select * from user where id = 1 for update;
# 2⃣️ 命令行2,执行
select * from user where id = 2 for update;
# 3⃣️ 命令行1,执行
select * from user where id = 2 for update;
# 4⃣️ 命令行2,执行
select * from user where id = 1 for update;

# 都在等待对方释放锁,所以死锁了
Deadlock found when trying to get lock; try restarting transaction
死锁避免

1 调整逻辑顺序,比如将上面死锁的演示顺序调整为 1324,这样只会出现等待,而不会死锁
2 降低事务级别,串行化
3 一般在事务中不使用悲观锁 for update,使用乐观锁代替
4 除了使用乐观锁代替,还能使用分布式锁代替

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值