当前位置:网站首页>[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
边栏推荐
- Image fusion -- challenges, opportunities and Countermeasures
- Tidb backup and recovery introduction
- Migrate data from SQL files to tidb
- IP lab, the first weekly recheck
- MFC 给列表控件发送左键单击、双击、以及右键单击消息
- 从表中名称映射关系修改视频名称
- Golang DNS write casually
- 2.10transfrom attribute
- sys.argv
- Vocabulary notes for postgraduate entrance examination (3)
猜你喜欢

ESP series pin description diagram summary

C语言 - 位段

Pyqt5 development tips - obtain Manhattan distance between coordinates

vulnhub hackme: 1

Nft智能合约发行,盲盒,公开发售技术实战--合约篇

wincc7.5下载安装教程(Win10系统)

The State Economic Information Center "APEC industry +" Western Silicon Valley will invest 2trillion yuan in Chengdu Chongqing economic circle, which will surpass the observation of Shanghai | stable

Nft智能合约发行,盲盒,公开发售技术实战--拼图篇

NFT smart contract release, blind box, public offering technology practice -- contract

Wincc7.5 download and installation tutorial (win10 system)
随机推荐
Wireshark grabs packets to understand its word TCP segment
LDAP Application Section (4) Jenkins Access
synchronized 解决共享带来的问题
2022 Inner Mongolia latest construction tower crane (construction special operation) simulation examination question bank and answers
Leetcode question brushing (5.31) string
IP lab, the first weekly recheck
Analysis of pointer and array written test questions
Restore backup data on S3 compatible storage with br
"Designer universe" APEC design +: the list of winners of the Paris Design Award in France was recently announced. The winners of "Changsha world center Damei mansion" were awarded by the national eco
Pyqt5 development tips - obtain Manhattan distance between coordinates
Use dumping to back up tidb cluster data to S3 compatible storage
CISP-PTE实操练习讲解
[Yugong series] February 2022 U3D full stack class 010 prefabricated parts
[luatos-air551g] 6.2 repair: restart caused by line drawing
Analysis of Top1 accuracy and top5 accuracy examples
CAD ARX 获取当前的视口设置
[research materials] 2022 China yuancosmos white paper - Download attached
[t31zl intelligent video application processor data]
MFC sends left click, double click, and right click messages to list controls
Summary of MySQL index failure scenarios