Mysql lock mechanism
-
- I. Overview
- Two and three locks (table, row, page lock)
I. Overview
(1) Definition
(2) Example introduction: life shopping
(3) Classification of locks
① From the type of data operation (read, write)
读锁(共享锁):针对同一份数据,多个读操作可以同时进行而不会互相影响
写锁(排它锁):当前写操作没有完成前,它会阻断其他写锁和读锁。
② From the granularity of data operation
- Table lock
- Row lock
Two and three locks (table, row, page lock)
(1) Table lock (partial reading)★
① Features
偏向MyISAM存储引擎,开销小,加锁快,无死锁,锁定粒度大,发生锁冲突的概率最高,并发最低
② Case analysis
1. Add/release table lock:
Increase table lock statement
lock table 表名1 read(write), 表名2 read(write) .....;
Release table lock statement
unlock tables;
2. Add read lock:
3. Add write lock:
③ Case conclusion
④ Table lock analysis
(2) Row lock (partial writing)★
① Features
偏向InnoDB存储引擎,开销大,加锁慢;会出现死锁;锁定粒度最小,发生锁冲突的概率最低,并发度也最高。
InnoDB与MyISAM的最大不同有两点:
一是支持事务(TRANSACTION);
二是采用了行级锁
② Row lock support transaction (review old knowledge)
1. Transaction (Transation) and its ACID attributes
2. Problems caused by concurrent transaction processing
-
Update loss (Lost Update)
-
Dirty read (Dirty Reads)
-
Non-repeatable read (Non-Repeatable Reads)
-
Magic Reading (Phantom Reads)
3. Transaction isolation level
查看事务的隔离级别:show variables like "%tx_isolation%";
③ Case analysis
1. Basic demonstration of row lock
2. No index row lock is upgraded to table lock
varchar 不用 ' ' 导致系统自动转换类型, 行锁变表锁
3. Gap lock hazards
4. Interview questions: how to lock a line for the regular exam
④ Case conclusion
⑤ Row lock analysis
检查innodb的行锁状态:show status like "%innodb_row_lock%";
⑥ Optimization suggestions
- As far as possible, all data retrieval is completed through the index , to avoid the upgrade of non-indexed row locks to table locks
- Design the index reasonably to minimize the scope of the lock
- Possible to reduce the search condition , to avoid gaps lock
- Try to control the size of the transaction , reduce the amount of locked resources and the length of time
- Low-level transaction isolation possible
(3) Page lock (understand)
开销和加锁时间界于表锁和行锁之间:会出现死锁;
锁定粒度界于表锁和行锁之间,并发度一般。