当前位置:网站首页>[MySQL] lock
[MySQL] lock
2022-07-06 08:23:00 【If you dare to fly, you will have the sky】
lock
A lock is a mechanism by which a computer coordinates multiple processes or threads to access a resource concurrently . In the database , Data is also a shared resource . How to ensure the consistency of data concurrent access 、 Validity is a problem that all databases must solve , Lock conflicts are also an important factor affecting the performance of concurrent database access .
- Global lock : Lock all tables in the database .
- Table lock : Lock the whole table with each operation .
- Row-level locks : Each operation locks the corresponding row data .
Global lock
Global lock is to lock the whole database instance , After locking, the entire instance is in a read-only state , Subsequent inclusion DML sentence 、DDL The transaction commit statements of the statement will be blocked . Its typical use scenario is to make a logical backup of the whole database , Lock all tables , To get a consistent view , Ensure data integrity .
# Add global lock
flush tables with read lock;
# The data backup
# Windows Command line
mysqldump -h39.105.19.217 -uroot –p123456 dataBaseName > scriptName.sql
# Release the lock
unlock tables;
characteristic :
- If it is backed up on the primary database , The update cannot be performed during the backup , Business basically stopped .
- If you are backing up from a library , During the backup, the slave database cannot synchronize the binary logs from the master database , Will cause master-slave delay .
# InnoDB Storage engine , Consistent data backup without lock
mysqldump --single-transaction -uroot –p123456 itcast > itcast.sql
Table lock
Table lock , Lock the whole table with each operation . Large locking size , The probability of lock conflict is high , Low concurrency . Apply to MyISAM、InnoDB Wait for the storage engine . For table lock , It is mainly divided into the following three categories :
- Table locks
- Metadata lock (meta data lock, MDL)
- Intent locks
Table locks
Read the lock ( Shared lock )
Write lock ( Exclusive lock )
# Add read lock
lock tables tableName read;
# Add write lock
lock tables tableName write;
# Release the lock
unlock tables;
Conclusion : Read locks do not block reads from other clients , But it will block writing . The write lock will block the reading of other clients , It will block the writing of other clients .
Metadata lock
MySQL5.5 Introduce metadata lock , When accessing a table, it will be locked automatically . Metadata can be simply understood as the table structure of a table , When a table involves uncommitted transactions , You cannot modify the table structure of this table . Metadata lock is to avoid DML And DDL Conflict , Ensure the correctness of reading and writing .
When adding to a table 、 Delete 、 Change 、 When checking the operation , Shared lock of Canadian dollar data lock . When changing the table structure , Exclusive lock of Canadian dollar data lock .
# Check the metadata lock in the database
select object_type,object_schema,object_name,lock_type,lock_duration from performance_schema.metadata_locks;
Intent locks
for fear of DML When executed , Conflict between row lock and table lock , stay InnoDB Intention lock is introduced into the storage engine , So that the table lock doesn't have to check every row
Whether the data is locked , Use intent lock to reduce the checking of table lock .
- Intention sharing lock (IS): By statement select … lock in share mode add to . Compatible with shared locks of table locks , Exclusive locks with table locks are mutually exclusive .
- Intention exclusive lock (IX): from insert、update、delete、select…for update add to . Shared locks and exclusive locks with table locks are mutually exclusive .
- Intent locks are not mutually exclusive , Once the transaction is committed , Intention sharing lock 、 The intentional exclusive lock will be automatically released .
# Check the locking of intention lock and row lock
select object_schema,object_name,index_name,lock_type,lock_mode,lock_data from performance_schema.data_locks;
Row-level locks
Row-level locks , Each operation locks the corresponding row data . The locking granularity is small , The probability of lock conflict is low , High concurrency . Apply to InnoDB In the storage engine .InnoDB The data is organized based on indexes , Row locking is achieved by locking the index items on the index , Instead of adding to the record
lock . For row level locks , It is mainly divided into the following three categories :
Row lock : Lock a single line record , Prevent other transactions from... On this line update and delete. stay Read Commit、Repeatable Read Both isolation levels support .
Clearance lock : Lock index record gap ( This record is not included ), Ensure that the index record gap remains unchanged , Prevent other transactions from going on in this gap insert, And then there's magic reading . stay Repeatable Read Support at isolation level .
Temporary key lock : Combination of row lock and clearance lock , Lock the data at the same time , And lock the gap in front of the data . stay Repeatable Read Support at isolation level .
Row lock
InnoDB The storage engine implements the following two types of row locks :
- Shared lock (S): Allow a transaction to read a line , Prevent other transactions from obtaining exclusive locks on the same dataset .
- Exclusive lock (X): Allow to get transaction update data of exclusive lock , Prevent other transactions from obtaining shared locks and exclusions for the same dataset
lock .
When searching for a unique index , When performing equivalence matching on existing records , It will be automatically optimized as row lock .InnoDB The row lock of the storage engine is the lock added to the index , When retrieving without indexing , All records in the table will be locked , At this point, it will be upgraded to table lock .
As soon as the client gets id by 1 This line of shared locks , Second, the client can obtain id by 3 The exclusive lock of this line , Because it's not the same row of data . And if client 2 wants to get id by 1 Exclusive locks in this line , It's going to be blocked , Think that shared locks and exclusive locks are mutually exclusive .
When a client , perform update sentence , Would be id by 1 We'll lock our records . Client 2 , If so update Statement update id by 1 The data of , For id by 1 Data with exclusive lock , But client 2 will be blocked , Because exclusive locks are mutually exclusive . Until the client commits the transaction , Will release the row lock of this row , At this time, the client 2 is unblocked .
As soon as the client starts the transaction , And implement update sentence , to update name by Lily The data of , That is to say id by 19 The record of . Then update... In client 2 id by 3 The record of , But not directly , It's going to be blocked , Why? ? Because at this time, the client is based on name When the field is updated name The field has no index , If there is no index , At this point, the row lock will be upgraded to a table lock ( Because row locks are locks on index entries , and name No index ).
# Check the locking of intention lock and row lock
select object_schema,object_name,index_name,lock_type,lock_mode,lock_data from performance_schema.data_locks;
Clearance lock and temporary key lock
By default ,InnoDB Storage engine in Repeatable Read Transaction isolation level running , Search and index scan with keylock , To prevent unreal reading .
Equivalent query on Index ( unique index ), When locking records that do not exist , Optimized for clearance lock .
Equivalent query on Index ( Non unique index ), When traversing to the right, the last value does not meet the query requirements , Key lock degenerates into clearance lock .
InnoDB The storage engine uses B+ Tree index , Leaf nodes are ordered two-way linked lists . If , According to this secondary index, the query value is 18 The data of , And add a shared lock , We're just locking 18 Is this all right ? Not at all , Because it's a non unique index , There may be more than one... In this structure 18 The existence of , therefore , Will continue to look back when locking , Find a value that does not meet the condition ( In the current case, that is 29). It will be right at this time 18 Add temporary key lock , Also on 29 Lock the previous gap .
- Range query on Index ( unique index ), Access to the first value that does not satisfy the condition .
The query criteria are id>=19, And add a shared lock . At this point, we can use the existing data in the database table , Divide the data into three parts :[19]、(19,25]、(25,+∞]. So the database locking situation is ,19 With a row lock ,25 The key lock of ( contain 25 And 25 The gap before ), Positive infinite presence
Key lock ( Positive infinity and the gap before ).
Be careful : The only purpose of a gap lock is to prevent other transactions from inserting gaps . Gap locks can coexist , A gap lock adopted by one transaction will not prevent another transaction from adopting a gap lock on the same gap .
Reference resources :https://www.bilibili.com/video/BV1Kr4y1i7ru
边栏推荐
- [2022 Guangdong saim] Lagrange interpolation (multivariate function extreme value divide and conquer NTT)
- Char to leading 0
- Use Alibaba icon in uniapp
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- 在 uniapp 中使用阿里图标
- Easy to use tcp-udp_ Debug tool download and use
- CAD ARX 获取当前的视口设置
- File upload of DVWA range
- Analysis of Top1 accuracy and top5 accuracy examples
- Hcip day 16
猜你喜欢
将 NFT 设置为 ENS 个人资料头像的分步指南
National economic information center "APEC industry +": economic data released at the night of the Spring Festival | observation of stable strategy industry fund
【云原生】手把手教你搭建ferry开源工单系统
Online yaml to CSV tool
Nacos Development Manual
你想知道的ArrayList知识都在这
Résumé des diagrammes de description des broches de la série ESP
Circular reference of ES6 module
C语言自定义类型:结构体
"Friendship and righteousness" of the center for national economy and information technology: China's friendship wine - the "unparalleled loyalty and righteousness" of the solidarity group released th
随机推荐
Huawei cloud OBS file upload and download tool class
Mobile Test Engineer occupation yyds dry goods inventory
MFC sends left click, double click, and right click messages to list controls
LDAP應用篇(4)Jenkins接入
2022.02.13 - NC002. sort
IOT -- interpreting the four tier architecture of the Internet of things
C language - bit segment
让学指针变得更简单(三)
Résumé des diagrammes de description des broches de la série ESP
Wireshark grabs packets to understand its word TCP segment
String to leading 0
2022 Inner Mongolia latest water conservancy and hydropower construction safety officer simulation examination questions and answers
Pointer advanced --- pointer array, array pointer
Use br to back up tidb cluster data to S3 compatible storage
升级 TiDB Operator
How to use information mechanism to realize process mutual exclusion, process synchronization and precursor relationship
File upload of DVWA range
[MySQL] database stored procedure and storage function clearance tutorial (full version)
hcip--mpls
Leetcode question brushing (5.31) string