当前位置:网站首页>MySQL Advanced Series: locks - locks in InnoDB
MySQL Advanced Series: locks - locks in InnoDB
2022-06-24 16:03:00 【Mr Ji】
Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 6 God , Click to see the event details
MySQL lock -InnoDB In the case of lock
mysql> select @@version;
+-----------+
| @@version |
+-----------+
| 5.7.21 |
+-----------+
1 row in set (0.01 sec)
One , Basic introduction of lock
Relative to other databases ,MySQL The locking mechanism is relatively simple , The most striking features are different Storage engine Different lock support mechanisms . such as ,MyISAM and MEMORY The storage engine uses table level locks (table-level locking);InnoDB The storage engine supports both row level locks (row-level locking), Table level locks are also supported , But the default is row level locking .
Table lock : Low overhead , Locked fast ; A deadlock will not occur ; Large locking size , The highest probability of lock collisions , Lowest degree of concurrency .
Row-level locks : Spending big , Lock the slow ; A deadlock occurs ; Locking granularity minimum , The lowest probability of lock collisions , The highest degree of concurrency .
Row level lock type :
Record Lock( Record locks ): Be a record lock ( Lock a single record )
The record lock will only lock the indexed records , If InnoDB The storage table does not have any indexes when it is created , Then the lock will be locked with an implicit primary key , Here's the picture
Gap Lock( Clearance lock ): Lock a range , Not including the record itself ( Only lock the front of the data GAP)
The lock shown in the following figure is GAP lock , No other transactions are allowed in the index column 8 Insert a new record in the previous gap , That is to say (3 , 8) This interval .gap lock The function of is only to prevent the insertion of phantom records
Next-Key Lock( Temporary key lock ): Lock the record and the front of the record at the same time GAP, That is to say Next-Key Lock = Record Lock + Gap Lock.
Two , Classification of locks
Shared lock Share Locks ( abbreviation S lock , Belongs to the row lock )
Exclusive lock Exclusive Locks ( abbreviation X lock , Belongs to the row lock )
Intention sharing lock Intention Share Locks ( abbreviation IS lock , It belongs to watch lock )
Intention exclusive lock Intention Exclusive Locks ( abbreviation IX lock , It belongs to watch lock )
Self increasing lock AUTO-INC Locks( It belongs to watch lock )
The following describes each type of lock in detail , Let's build one first innodb Table of ,sql as follows
create table tab_with_index(id int,name varchar(10)) engine=innodb;
alter table tab_with_index add index id(id);
insert into tab_with_index values(1,'1'),(2,'2'),(3,'3'),(4,'4');
Shared lock
Shared lock means that multiple transactions can share a lock for the same data , Can access the database , But it can only be read but not modified ;
Business A:
select * from tab_with_index lock in share mode;
Business B:
select * from tab_with_index where id =1; // Can query data
update tab_with_index set name = 'aa' where id = 1 ;
Be careful : The modification statement here will block , Until transaction A The operation cannot succeed until it is submitted .
Exclusive lock
Exclusive locks cannot coexist with other locks , For example, a transaction obtains the exclusive lock of a data row , Other transactions cannot acquire the lock of the row , Only the current transaction that obtains the exclusive lock can modify the data .(delete,update,create The default is exclusive lock )
Business A:
select * from tab_with_index where id =1 for update;
Business B:
select * from tab_with_index where id =1; // You can get results
select * from tab_with_index where id =1 for update; // jam
select * from tab_with_index where id = 1 lock for share mode; // jam
Be careful : Business B Two sql Will be blocked , That is, you cannot obtain shared locks or exclusive locks , Until transaction A The operation cannot succeed until it is submitted .
Intentional shared lock and intentional exclusive lock
Intention sharing lock : Indicates that the transaction is ready to add a shared lock to the data row , That is to say, a data row must obtain the data of the table before adding a shared lock IS lock .
Intention exclusive lock : Indicates that the transaction is ready to add an exclusive lock to the data row , That is to say, before a data row is locked with an exclusive lock, it is necessary to obtain the IX lock .
IS Lock and IX Locks are table level locks , Their proposal is only to add a table level S Lock and X When locking, it can quickly determine whether the records in the table are locked , To avoid traversing to see if there are locked records in the table , That is to say, in fact IS Lock and IX Locks are compatible ,IX Lock and IX Locks are compatible . 《MySQL How it works 》
Self increasing lock
A special table level lock for auto incrementing columns .
show variables like 'innodb_autoinc_lock_mode';
-- The default value is 1, Stands for continuous , If the transaction is not committed ID Permanent loss
3、 ... and ,InnoDB lock
1、 Affairs and ACID attribute
The business is made up of a group of SQL A logical processing unit made up of statements , The transaction is 4 attribute , Usually called transactional ACID attribute .
Atomicity (Actomicity): A transaction is an atomic unit of operation , Its modification of data , Or do it all , Or none of them . Uniformity (Consistent): At the beginning and end of the transaction , Data must be consistent . Isolation, (Isolation): The database system provides a certain isolation mechanism , Ensure that transactions are not affected by external concurrent operations “ Independent ” Environmental execution . persistence (Durable): After the transaction completes , Its modification of data is permanent , Even if there is a system failure, it can keep .
2、 Problems caused by concurrent transactions
Compared to serial processing , Concurrent transaction processing can greatly increase the utilization of database resources , Improve transaction throughput of database system , So it can support more users' concurrent operation , But at the same time , It will bring some problems :
Dirty reading : A transaction is modifying a record , Before this transaction is submitted , The data of this record is inconsistent ; At this time , Another transaction also reads the same record , If not controlled , The second transaction reads these “ dirty ” The data of , And make further treatment accordingly , Uncommitted data dependency will be generated . This phenomenon is vividly called “ Dirty reading ”
It can't be read repeatedly : A transaction has changed in reading some data 、 Or some records have been deleted ! This phenomenon is called “ It can't be read repeatedly ”.
Fantasy reading : A transaction re reads the previously retrieved data according to the same query criteria , However, it is found that other transactions have inserted new data satisfying their query criteria , This phenomenon is called “ Fantasy reading ”
The above problems are all the problems of database read consistency , It can be guaranteed through the isolation mechanism of transactions .
The more strict the transaction isolation of the database , The smaller the concurrent side effects , But the more it costs , Because the essence of transaction isolation is to serialize transactions to a certain extent , You need to decide which isolation level to use according to your specific business needs
| Dirty reading | It can't be read repeatedly | Fantasy reading | |
|---|---|---|---|
| read uncommitted | √ | √ | √ |
| read committed | √ | √ | |
| repeatable read | √ | ||
| serializable |
It can pass the inspection InnoDB_row_lock State variables are used to analyze the contention of row locks on the system :
mysql> show status like 'innodb_row_lock%';
+-------------------------------+-------+
| Variable_name | Value |
+-------------------------------+-------+
| Innodb_row_lock_current_waits | 0 |
| Innodb_row_lock_time | 18702 |
| Innodb_row_lock_time_avg | 18702 |
| Innodb_row_lock_time_max | 18702 |
| Innodb_row_lock_waits | 1 |
+-------------------------------+-------+
-- If lock contention is found to be serious , Such as InnoDB_row_lock_waits and InnoDB_row_lock_time_avg The value of is relatively high
3、InnoDB Line lock mode and locking method of
Shared lock (S) : Also called read lock (lock in share mode). Allow a transaction to read a line , Prevent other transactions from obtaining exclusive locks for the same dataset . If business T For data objects A add S lock , The transaction T You can read A But it can't be modified A, Other affairs can only be right again A Add S lock , Instead of X lock , until T Release A Upper S lock . This ensures that other things can be read A, But in T Release A Upper S You can't do it before you lock it A Make any changes . Exclusive lock (X) : Also known as write lock (for update). Allow to get transaction update data of exclusive lock , Prevent other transactions from acquiring the same dataset, sharing read locks and exclusive write locks . If business T For data objects A add X lock , Business T You can read A You can also modify A, Other affairs can no longer be right A Add any locks , until T Release A The lock on the .
mysql InnoDB The default data modification statement of the engine :update,delete,insert Will automatically add an exclusive lock to the data involved ,select Statement will not add any lock type by default , If an exclusive lock is added, it can be used select …for update sentence , Add shared lock to use select … lock in share mode sentence . Therefore, data rows with exclusive locks cannot be modified in other transactions , It can't pass for update and lock in share mode Query data by lock , But you can go straight through select …from… Query data , Because normal queries don't have any locking mechanism .
4、InnoDB Implementation of row lock
InnoDB Line lock is by giving Indexes To implement the index of , This point MySQL And Oracle Different , The latter is realized by locking the corresponding data row in the data block .InnoDB This row lock implementation feature means : Data is retrieved only through index conditions ,InnoDB To use row level locks , otherwise ,InnoDB Table locks will be used !
1、 When querying without index criteria ,innodb Table locks are used instead of row locks
create table tab_no_index(id int,name varchar(10)) engine=innodb;
insert into tab_no_index values(1,'1'),(2,'2'),(3,'3'),(4,'4');
| session1 | session2 |
|---|---|
| set autocommit=0 select * from tab_no_index where id = 1; | set autocommit=0 select * from tab_no_index where id =2 |
| select * from tab_no_index where id = 1 for update | |
| select * from tab_no_index where id = 2 for update; |
session1 Only one row has an exclusive lock , however session2 When requesting exclusive locks for other rows , There will be lock waiting . The reason is that without an index ,innodb Only table locks can be used .
2、 Create a table with index for conditional query ,innodb Using row locks
create table tab_with_index(id int,name varchar(10)) engine=innodb;
alter table tab_with_index add index id(id);
insert into tab_with_index values(1,'1'),(2,'2'),(3,'3'),(4,'4');
| session1 | session2 |
|---|---|
| set autocommit=0 select * from tab_with_indexwhere id = 1; | set autocommit=0 select * from tab_with_indexwhere id =2 |
| select * from tab_with_indexwhere id = 1 for update | |
| select * from tab_with_indexwhere id = 2 for update; |
3、 because mysql The row lock of is the lock added for the index , It's not a lock on records , So while it's a record of visiting different people , But still unable to access specific data ( Here is the watch lock )
alter table tab_with_index drop index id;
insert into tab_with_index values(1,'4');
| session1 | session2 |
|---|---|
| set autocommit=0 | set autocommit=0 |
| select * from tab_with_index where id = 1 and name='1' for update | |
| select * from tab_with_index where id = 1 and name='4' for update although session2 Visited are and session1 Different records , But the lock is a specific table , So you need to wait for the lock |
summary
about InnoDB surface , This paper mainly discusses the following contents : (1)InnoDB Row locks are implemented based on indexes , If you don't access the data through the index ,InnoDB Can use watch lock . (2) At different levels of isolation ,InnoDB The lock mechanism is different from the consistent read strategy .
In understanding InnoDB After the lock feature , Users can design and SQL Adjust and other measures to reduce lock conflicts and deadlocks , Include :
- Try to use a lower isolation level ; Well designed index , And try to use index to access data , Make locking more accurate , So as to reduce the chance of lock conflict ;
- Choose a reasonable transaction size , Small transactions are less likely to have lock conflicts ;
- When explicitly locking a recordset , It's best to request a lock of sufficient level at once . For example, if you want to modify the data , It's better to apply for exclusive lock directly , Instead of applying for a shared lock first , Request exclusive lock when modifying , This is easy to cause deadlock ;
- When different programs access a set of tables , It should be agreed as much as possible to access the tables in the same order , For a watch , Try to access the rows in the table in a fixed order . This can greatly reduce the chance of deadlock ;
- Try to access data with equal conditions , This can avoid the effect of gap lock on concurrent insert ; Don't apply for more locks than you actually need ; Unless necessary , Do not show lock when querying ;
- For some particular business , Table locks can be used to increase processing speed or reduce the possibility of deadlock .
I'm Mr. Ji , Use output to force input and continue learning , Continue to share a series of technical articles , And the whole network is worth collecting good articles , Welcome to the official account , Be a continuously growing technical person .
mysql Advanced series of historical articles
( You can also read other related articles in the Nuggets column )
1. MySQL Advanced Series : Understand mysql Infrastructure ;
2. MySQL Advanced Series : Understand mysql Storage engine ;
3. MySQL Advanced Series :mysql in MyISAM and InnoDB What's the difference? ;
4. MySQL Advanced Series :mysql How to better select data types in table design ;
5. MySQL Advanced Series : How to use the paradigm in database design ;
6. MySQL Advanced Series : A detailed explanation explain Meaning of each field ;
7. MySQL Advanced Series : Why? mysql Use B+ Data structure as index ;
8. MySQL Advanced Series : Some basic knowledge of indexing you need to know ;
9. MySQL Advanced Series : How to create an index is more appropriate ;
10. MySQL Advanced Series : Principle and configuration of master-slave replication ;
11. MySQL Advanced Series :join The principle of connection -3 Species algorithm ;
12. MySQL Advanced Series : Transaction and transaction isolation level ;
13. MySQL Advanced Series : Multi version concurrency control mvcc The implementation of the ;
14. MySQL Advanced Series : One sql How is it carried out ;
15. MySQL Advanced Series : What you need to know MySQL journal ;
16. MySQL Advanced Series :MySQL Master slave replication and principle ;
17. MySQL Advanced Series :MySQL In the lock -MyISAM piece ;
边栏推荐
- B. Terry sequence (thinking + greed) codeforces round 665 (Div. 2)
- Installer la Bibliothèque imagemagick 7.1 et l'extension imagick de PHP
- Intelij 中的 Database Tools可以连接但是无法显示SCHEMA, TABLES
- MySQL development specification
- The equipment is connected to the easycvr platform through the national standard gb28181. How to solve the problem of disconnection?
- Nifi from introduction to practice (nanny level tutorial) - environment
- Pytorch 转置卷积
- [C language questions -- leetcode 12 questions] take you off and fly into the garbage
- Understanding openstack network
- [application recommendation] the hands-on experience and model selection suggestions of apifox & apipost in the recent fire
猜你喜欢

60 divine vs Code plug-ins!!

Intelij 中的 Database Tools可以连接但是无法显示SCHEMA, TABLES

Recommend several super practical data analysis tools

The penetration of 5g users of operators is far slower than that of 4G. The popularity of 5g still depends on China Radio and television

用 Oasis 开发一个跳一跳(一)—— 场景搭建

MySQL binlog

Solution to the problem that FreeRTOS does not execute new tasks

One article explains Jackson configuration information in detail

Most common usage of vim editor

使用阿里云RDS for SQL Server性能洞察优化数据库负载-初识性能洞察
随机推荐
日志记录真没你想的那么简单
2021-05-01: given an ordered array arr, it represents the points located on the X axis. Given a positive number k
Global and Chinese market for commercial barbecue smokers 2022-2028: Research Report on technology, participants, trends, market size and share
2021-04-25: given an array arr and a positive number m, the
安装ImageMagick7.1库以及php的Imagick扩展
How to implement SQLSERVER database migration in container
2021-04-24: handwriting Code: topology sorting.
60 divine vs Code plug-ins!!
2021-05-03: given a non negative integer num, how to avoid circular statements,
C. K-th Not Divisible by n(数学+思维) Codeforces Round #640 (Div. 4)
How to obtain ECS metadata
How to easily realize online karaoke room and sing "mountain sea" with Wang Xinling
April 30, 2021: there are residential areas on a straight line, and the post office can only be built on residential areas. Given an ordered positive array arr
The first in China! Tencent cloud key management system passes password application verification test
打破内存墙的新利器成行业“热搜”!持久内存让打工人也能玩转海量数据+高维模型
Step by step import RHEL image to Tencent cloud
Firefox browser uses plug-ins to set up proxy
Here comes Wi Fi 7. How strong is it?
B. Ternary Sequence(思维+贪心)Codeforces Round #665 (Div. 2)
Paper: Google TPU