mysql下事务和锁

来源:互联网 发布:软件销售提成方案 编辑:程序博客网 时间:2024/06/04 17:44

 

 

 

事务一

事务二

 

start transaction;

 

 

 

start transaction;

P1

selectc from a where a=1; 

 

 

 

update a set c=c+1where a=1;

P2

selectc from a where a=1 for update;

 

Q1

 

selectc from a where a=1; 

 

 

commit;

P3

selectc from a where a=1;

 

 

commit;

 

 

同一个事务中

select c from a where a=1 for update

select c from a where a=1

取出的值不一样

 

 

REPEATABLE READ(可重复读)

P1=P3=0

P2=Q1=1

READ COMMITTED

P1=0

P2=P3=Q1=1

 

 

 

 

事务一

事务二

 

start transaction;

 

 

 

 

P1

selectc from a where a=1; 

 

 

 

start transaction;

 

 

update a set c=c+1where a=1;

Q1

 

selectc from a where a=1; 

P2

selectc from a where a=1; 

 

 

 

commit;

P3

selectc from a where a=1;

 

 

 

 

 

 一致性的非锁定读:

通过Undo段实现,不同的隔离级别读取的快照数据不同

多版本并发控制(Multi Version Concurrency Control, MVCC)

 

REPEATABLE READ(可重复读)

P1=P2=P3=0

Q1=1

READ COMMITTED

P1=P2=0

P3=Q1=1

 

 

 

事务一

事务二

结果(更新后

读最新值)

 

start transaction;

 

 

 

 

start transaction;

 

Q1

 

selectc from a where a=1; 

0

 

 

update a set c=c+1where a=1;

 

Q1

 

selectc from a where a=1; 

1

 

 

commit;

 

P1

selectc from a where a=1;

 

1

 

 

 

 

 

事务一

事务二

结果(更新后

读最新值)

 

start transaction;

 

 

 

 

start transaction;

 

P1

selectc from a where a=1; 

 

0

 

 

update a set c=c+1where a=1;

 

Q1

 

selectc from a where a=1; 

1

 

update a set c=c+1where a=1;

 

 

 

 

commit;

 

P2

selectc from a where a=1;

 

3

 

 

 

 

 

 

 

事务一

事务二

 

begin;

 

P1

update a set a=2 where a=1;

 

 

 

begin;

Q1

 

update a set c=37 where a=1;

 

commit;

 

 

 

 写一致性

REPEATABLE READ(可重复读)

重新启动更新

READ COMMITTED

重新启动更新

 

事务一

事务二

next-key-lock

begin;

 

 

select c from a where a<3 lock in share mode;

 

 

 

begin;

 

 

Insert into a(a) select 1;

锁等待

Commit;

 

 

SELECT@@tx_isolation;

 

SET [SESSION |GLOBAL] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED |REPEATABLE READ | SERIALIZABLE}

SET  SESSION TRANSACTION ISOLATION LEVELREPEATABLE READ;


0 0