共享锁
- 主表和子表的情景,当插入子表的时候防止主表被删除,造成插入的字表没有对应的主表。该场景使用排它锁在并发插入子表的时候会变成串行操作,效率低
begin //开启事务
select 1 from 主表 where id=xxx lock in share mode //锁住主表的一条数据
insert 子表 //插入字表
commit
begin //开启事务
delete from 主表 where id=xxx
delete from 子表 where 关联id=xxx
commit
- 读取时如果有还未提交的更新,需要阻塞直到读取到最新的数据(实际没遇到这种场景,直接读取就可以,读取到最近已经提交事务的数据)
排它锁
- 更新数据的值依赖当前值。该场景使用共享锁当两个事务操作同一条数据时有死锁问题
begin
select * from table where id=xxx for update
根据查询的值处理得到要更新的值
update set xxx where id=xxx
commit
乐观锁
select value from table where id=xxx
根据value处理得到新值
update set value=新值 where id=xxx and value=旧值
网友评论