Mysql的锁机制

MySQL InnoDB的事务: ACID
A:原子性,通过undo log实现
I:隔离性,通过锁机制实现
D:持久性,通过redo log实现
C: 通过原子性、隔离性、持久性实现的

InnoDB:支持行级锁和表级锁;默认支持行级锁
MyISAM:支持表锁
Memory:支持表锁

OLTP: on line transcation process(行锁)
OLAP: on line Analysis process(表锁)

MyISAM表锁
MyISAM表的读操作与写操作之间,以及写操作之间是串行的
通过lock table person read locol,允许查询和插入的并行操作,这个时候读锁,可以添加新数据

1. 表共享读锁(Table Read Lock) : 不会阻塞其他用户对同一个表的读请求,但是会所有用户阻塞写请求
2. 表独占写锁(Table Write Lock):阻塞其他用户的读和写的请求;当前用户可以读、写

session1
A:lock table person write; //加写锁
A:select * from person;
A:insert into person value(1,'zhangsan')
session 2
B: select * from person; //阻塞
A:unlock tables; //释放锁
B: select * from person;//可以读取数据

Mysql的锁机制_第1张图片

InnoDB锁机制

Mysql的锁机制_第2张图片1.锁的类型
InnoDB默认修改操作,使用的是排他锁;select语句默认不加任何锁
(1)共享锁 - 读锁 – select … lock for share model

(2)排他锁 - 写锁 – select … for upadte
可以读取其他行的数据

2.InnoDB锁的实现
行锁是通过索引来实现的,如果没有索引,就是表锁;只有通过索引检索数据,才会使用行锁
(1)没有索引,则使用表锁

//假定person没有索引
A: set autocommit = 0;
B: set autocommit = 0;
A: select * from person where id =1 for update;// 针对id =1,行锁;但是因为没有索引,导致是表锁
B:select * from person where id = 2 for update//阻塞;因为表锁了
A: commit;

(2)有索引,则使用行锁,可以同时锁定不同行,进行写操作

// alter table add index (id)
A: set autocommit = 0;
B: set autocommit = 0;
A: select * from person where id =1 for update;// 针对id =1,行锁;
B:select * from person where id = 2 for update//针对 id 2,行锁
A: commit;

(3)如果使用相同的索引,锁定不同的行,则第二个事务要等待

// alter table add index (id)
A: set autocommit = 0;
B: set autocommit = 0;
A: select * from person where id =1 and name = 1 for update;// 针对id =1,行锁;
B:select * from person where id = 1 and name = 4 for update//阻塞;因为使用的相同索引id
A: commit;

你可能感兴趣的:(mysql)