当前位置:网站首页>[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
边栏推荐
- 根据csv文件某一列字符串中某个数字排序
- Asia Pacific Financial Media | "APEC industry +" Western Silicon Valley invests 2trillion yuan in Chengdu Chongqing economic circle to catch up with Shanghai | stable strategy industry fund observatio
- Image fusion -- challenges, opportunities and Countermeasures
- Asia Pacific Financial Media | designer universe | Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers
- Step by step guide to setting NFT as an ens profile Avatar
- The Vice Minister of the Ministry of industry and information technology of "APEC industry +" of the national economic and information technology center led a team to Sichuan to investigate the operat
- 图像融合--挑战、机遇与对策
- NFT smart contract release, blind box, public offering technology practice -- jigsaw puzzle
- PHP - Common magic method (nanny level teaching)
- Circuit breaker: use of hystrix
猜你喜欢

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

将 NFT 设置为 ENS 个人资料头像的分步指南

Make learning pointer easier (3)

好用的TCP-UDP_debug工具下载和使用

Easy to use tcp-udp_ Debug tool download and use
![[cloud native] teach you how to build ferry open source work order system](/img/fb/507f763791235bd00bc8201e5d7741.png)
[cloud native] teach you how to build ferry open source work order system

The resources of underground pipe holes are tight, and the air blowing micro cable is not fragrant?

Deep learning: derivation of shallow neural networks and deep neural networks

指针和数组笔试题解析

Secure captcha (unsafe verification code) of DVWA range
随机推荐
从 SQL 文件迁移数据到 TiDB
logback1.3. X configuration details and Practice
[untitled]
Artcube information of "designer universe": Guangzhou implements the community designer system to achieve "great improvement" of urban quality | national economic and Information Center
How to use information mechanism to realize process mutual exclusion, process synchronization and precursor relationship
Analysis of pointer and array written test questions
图像融合--挑战、机遇与对策
leetcode刷题 (5.29) 哈希表
Wireshark grabs packets to understand its word TCP segment
Use br to back up tidb cluster data to S3 compatible storage
Asia Pacific Financial Media | "APEC industry +" Western Silicon Valley invests 2trillion yuan in Chengdu Chongqing economic circle to catch up with Shanghai | stable strategy industry fund observatio
[luatos-air551g] 6.2 repair: restart caused by line drawing
CAD ARX 获取当前的视口设置
Erc20 token agreement
根据csv文件某一列字符串中某个数字排序
Uibehavior, a comprehensive exploration of ugui source code
Introduction to number theory (greatest common divisor, prime sieve, inverse element)
NFT smart contract release, blind box, public offering technology practice -- jigsaw puzzle
Use Alibaba icon in uniapp
VMware virtualization cluster