The use of locks in MySQL (global, table-level, row-level locks)

        A lock is a mechanism by which a computer coordinates concurrent access to a resource by multiple processes or threads. In a database, in addition to traditional contention for computing resources (CPU, RAM, I/O), data is also a resource shared by many users. How to ensure the consistency and validity of concurrent access to data is a problem that all databases must solve, and lock conflicts are also an important factor affecting the performance of concurrent access to databases. From this perspective, locks are particularly important and more complex for databases.

        Locks in MySQL are divided into the following three categories according to the granularity of locks: 

  • Global lock : locks all tables in the database.
  • Table-level lock : each operation locks the entire table.
  • Row-level lock : Each operation locks the corresponding row data.

Next, we will introduce these three aspects in turn:

global lock

        The global lock is to lock the entire database instance. After locking, the entire instance is in a read-only state. Subsequent DML write statements, DDL statements, and transaction commit statements that have been updated will be blocked.

        Its typical usage scenario is to do a logical backup of the entire database and lock all tables to obtain a consistent view and ensure data integrity. Next, let's look at the specific use:

①Add a global lock

flush tables with read lock ;

②Data backup

mysqldump -uroot –p1234 itcast > itcast.sql
-- 其中itcast是要备份的数据库的名称,itcast.sql是备份后的存储路径文件名
-- 注意,此命令不是mysql的命令,不能在mysql中执行,需要在windows或linux命令行中执行

Release the lock

unlock tables ;

        Adding a global lock to the database is a relatively heavy operation, and there are the following problems:

  • If it is backed up on the main library, no updates can be performed during the backup period, and the business basically has to be shut down.
  • If it is backed up on the slave library, the slave library cannot execute the binary log (binlog) synchronized from the master library during the backup period, which will cause master-slave delay.

Note: In the InnoDB engine, we can add the parameter --single-transaction parameter during backup to complete the consistent data backup without locking: mysqldump --single-transaction -uroot –p123456 itcast > itcast.sql

table lock

        Table-level locks lock the entire table for each operation. The locking granularity is large, the probability of lock conflicts is the highest, and the concurrency is the lowest. Applied in storage engines such as MyISAM, InnoDB, and BDB.

Table-level locks are mainly divided into the following three categories:

  • table lock
  • Meta data lock (meta data lock, MDL)
  • intent lock 

① watch lock

        For table locks, there are two types: table shared read lock (read lock) , table exclusive write lock (write lock) 

        If a shared read lock is added, this client and other clients can only read and cannot write; if an exclusive write lock is added, this client can both read and write, while other clients can neither read , can not write. 

-- 加锁
lock tables 表名... read/write。
-- 释放锁
unlock tables / 客户端断开连接 。

② Metadata lock (MDL)

The MDL locking process is automatically controlled by the system and does not need to be used explicitly. It will be added automatically         when accessing a table . The main function of MDL lock is to maintain the data consistency of table metadata. When there are active transactions on the table, the metadata cannot be written. In order to avoid conflicts between DML (addition, deletion, modification and query) and DDL (operation table structure), ensure the correctness of reading and writing.

        The metadata here can be simply understood as the table structure of a table . That is to say, when a certain table involves uncommitted transactions, the table structure of this table cannot be modified.

Metadata locks can be divided into the following two categories:

  • MDL shared read lock : When adding, deleting, modifying and querying a table, the MDL shared lock is automatically added
  • MDL exclusive write lock : when the table structure is changed, the MDL exclusive lock is automatically added

-- 查看元数据锁的加锁情况
select object_type,object_schema,object_name,lock_type,lock_duration from performance_schema.metadata_locks ;

③ Intent lock 

        In order to avoid conflicts between row locks and table locks added during DML execution, intent locks are introduced in InnoDB, so that table locks do not need to check whether each row of data has row locks, and use intent locks to reduce table lock checks. That is: when performing DML operations, row locks will be added to the rows involved, and intention locks will also be added to the table. And other clients, when adding a table lock to this table, will determine whether the table lock can be successfully added according to the intent lock added to the table, instead of judging the row lock situation row by row.

Intention locks can be divided into two categories:

  • Intention shared lock (IS) : added by the statement select ... lock in share mode. Compatible with table lock shared lock (read), mutually exclusive with table lock exclusive lock (write).
  • Intent exclusive lock (IX) : added by insert, update, delete, select...for update. Shared locks (read) and exclusive locks (write) are mutually exclusive with table locks, and intent locks are not mutually exclusive

Once the transaction is committed, the intent shared lock and the intent exclusive lock will be released automatically. 

-- 查看意向锁及行锁的加锁情况
select object_schema,object_name,index_name,lock_type,lock_mode,lock_data from performance_schema.data_locks;

row level lock

        Row-level lock, each operation locks the corresponding row data. The locking granularity is the smallest, the probability of lock conflicts is the lowest, and the concurrency is the highest. Applied in the InnoDB storage engine.

        InnoDB's data is organized based on indexes, and row locks are implemented by locking index items on the index, rather than locking records. For row-level locks, there are three main categories:

  • Row lock (Record Lock) : A lock that locks a single row record, preventing other transactions from updating and deleting this row. It is supported under both RC and RR isolation levels.
  • Gap Lock : Lock the index record gap (excluding this record), ensure that the index record gap remains unchanged, and prevent other transactions from inserting in this gap, resulting in phantom reading. Both are supported under the RR isolation level.
  • Next-Key Lock : A combination of row lock and gap lock, which locks data at the same time and locks the Gap in front of the data. Supported under RR isolation level.

① row lock

        InnoDB implements the following two types of row locks:

  • Shared lock (S) : Allows one transaction to read a row, preventing other transactions from obtaining exclusive locks on the same data set.
  • Exclusive lock (X) : Allow transactions that acquire exclusive locks to update data, preventing other transactions from acquiring shared and exclusive locks on the same data set. 

By default, InnoDB runs at the REPEATABLE READ transaction isolation level, and InnoDB uses next-key locks for searches and index scans to prevent phantom reads.

  • When searching against a unique index , when performing equivalent matching on existing records, it will be automatically optimized to a row lock .
  • InnoDB's row lock is a lock for the index. If you do not retrieve data through the index condition, InnoDB will lock all the records in the table, and then it will be upgraded to a table lock.

② Gap lock / Pro key lock

        By default, InnoDB runs at the REPEATABLE READ transaction isolation level, and InnoDB uses next-key locks for searches and index scans to prevent phantom reads.

  • The equivalent query on the index (unique index) is optimized as a gap lock when locking a record that does not exist.
  • In the equivalent query on the index (ordinary index), when the last value does not meet the query requirements when traversing to the right, the next-key lock degenerates into a gap lock (that is, the current value and the gap behind it are locked).
  • The range query on the index (unique index) will access the first value that does not meet the condition (that is, lock the range). 
Notice:
        The sole purpose of a gap lock is to prevent other transactions from inserting into the gap. Gap locks can coexist, and a gap lock taken by one transaction does not prevent another transaction from taking a gap lock on the same gap.

Guess you like

Origin blog.csdn.net/weixin_52850476/article/details/124767175