Table of Contents
1. InnoDB table-level locks
2. Intention shared lock and intention exclusive lock
3. Operation
3. Lock optimization suggestions
Home Database Mysql Tutorial What are MySQL's intent shared locks, intent exclusive locks and deadlocks?

What are MySQL's intent shared locks, intent exclusive locks and deadlocks?

May 27, 2023 pm 10:22 PM
mysql

    1. InnoDB table-level locks

    Row-level locks should usually be used to ensure the integrity of transactions, and this is also a common reason for choosing the InnoDB engine. one. However, in individual cases, table-level locks may also be required.

    The transaction needs to update most or all of the data, and the table is relatively large. If the default row lock is used, not only will the transaction execution efficiency be low, but it may also cause other transactions to wait for a long time and lock conflicts. The transaction involves multiple tables. , which is more complicated and is likely to cause deadlock and rollback of a large number of transactions.

    When we want to obtain the table lock, execute the following command:

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    When using table locks, efficiency issues involved:
    To obtain a shared lock S or an exclusive lock X on a table, you must first make sure that the table has not been acquired by other transactions. After X lock, the data in this table has not been acquired by other transactions.

    Suppose we have 10 million data in this table, how to determine which rows of these 10 million data have X locks?
    If you want to obtain the S lock of the table, you need to determine which rows in the table have X locks. If some rows have X locks, you cannot obtain the S lock or X lock of this table. There is no better way except checking one by one, which leads to the problem of low efficiency.

    The inefficiency caused by the need to add table locks is to traverse the data one by one to determine whether some data has been added with row locks. low problem. The intention shared lock and intention exclusive lock we are learning here can be solved. When you want to obtain the X lock of the table, you no longer need to check which row locks in the table are occupied by (X or S), you only need to quickly check IX Just lock it with IS.

    2. Intention shared lock and intention exclusive lock

    • Intention shared lock (IS lock): Transaction plan adds row shared lock to the record , before a transaction adds a shared lock to a row of records, it must first obtain the IS lock of the table

    • Intention exclusive lock (IX lock): The transaction plan adds a record to the IS lock Row exclusive lock. Before a transaction adds an exclusive lock to a row record, it must first obtain the IX lock of the table

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    • ##Before adding row locks, the IS or IX lock of the table added by the InnoDB storage engine

    • intention locks are

      compatible . There will be no conflict. It is mainly to assist others to speed up the efficiency when acquiring table locks.

    • The purpose of intention lock is to obtain table locks more efficiently (X and X in the table S refers to

      table lock, not row lock!)

    • Intention lock is

      table-level lock, coordinates table lock and Row lock coexistence . The main purpose is to show that a transaction is locking a row or trying to lock a row.

    Analyze transaction 1 to obtain the row X lock and transaction 2 to obtain the table S lock:

    When transaction 1 needs to give the 10th row of data to the table When adding an X lock, the InnoDB storage engine automatically adds an IX lock to the entire table. When transaction 2 wants to acquire the S lock of the entire table, it sees that another transaction has acquired the IX lock on this table, which means that there must be some data in this table that has been added to the X lock, which results in Transaction 2 cannot add S lock to the entire table. At this time, transaction 2 can only wait and cannot successfully obtain the table S lock

    3. Deadlock

    1. Deadlock in the database

    MyISAM table lock is deadlock free , this is because

    MyISAM does not support transactions, only table locks. It always obtains all required locks at one time, either all are satisfied or waiting, so no deadlock will occur. However, in InnoDB, except for transactions composed of a single SQL, the lock is obtained gradually, that is, the lock granularity is relatively small, which determines that deadlock is possible in InnoDB. Of course, if multiple tables are processed, deadlock may still occur.

    Deadlock problems are generally caused by ourselves. Similar to the deadlock situation in multi-thread programming, most of them are caused by the different order in which our multiple threads acquire multiple lock resources. resulting in deadlock problems. Therefore, when we use different code segments to update multiple tables in the database, these tables should be updated in the same order to prevent lock conflicts from causing deadlock problems.

    2. Deadlock scenarios and solutions

    The deadlock scenario is as follows:

    Transaction 1 successfully acquired row lock 1

    Transaction 2 Successfully acquired row lock 2
    ...
    Transaction 1 was unable to acquire row lock 2. While being blocked, there was no way to execute commit/rollback and could not release row lock 1
    Transaction 2 was unable to acquire row lock 1 and was blocked. There is no way to execute commit/rollback while blocking, and the row lock cannot be released. 2

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    All transactions are blocked, which is equivalent to all threads in the process being blocked, causing Deadlock problem.

    Methods to solve deadlocks: When multiple transactions/threads acquire multiple same resource locks, they should acquire resource locks in the same order.

    The transaction is blocked or deadlocked. Mysqld (MySQL Server daemon) is set with a timeout period for transaction blocking. The transaction will not be blocked for a long time and the transaction will be processed after the timeout. On failure, the currently held lock is automatically released.

    3. Operation

    Set manual commit and repeatable read isolation levels and open transactions

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    Query the table data, in repeatable The read isolation level uses the snapshot read provided by MVCC and does not lock.

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    Transaction 1 acquires the exclusive lock with id=7, and transaction 2 acquires the exclusive lock with id=8.

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    Transaction 1 acquires the exclusive lock with id=8 again, and blocking occurs

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    Transaction 2 acquires id= again The exclusive lock of 7 is blocked.

    What are MySQLs intent shared locks, intent exclusive locks and deadlocks?

    At this time, MySQL Server detects that a deadlock has occurred, so it unblocks transaction 1, rollbacks transaction 1, and releases it. The occupied row lock, so transaction 2 successfully obtained the exclusive lock with id=7

    3. Lock optimization suggestions

    • Under the premise that the business can be completed correctly, To ensure efficiency, try to use a lower isolation level (dirty reads must be avoided)

    • Design reasonable indexes and try to use indexes to access data, make locking more accurate, reduce the chance of lock conflicts, and improve concurrency capabilities

    • Choose a reasonable transaction size. The probability of lock conflicts for small transactions is small (the larger the transaction, the larger the transaction size. The more SQL there are, it may contain more locks on table resources and row resources, which increases the probability of lock conflicts.) When different programs access a group of tables, they should try to agree to access each table in the same order. For a table , access the rows in the table in a fixed order whenever possible. This can greatly reduce the chance of deadlock

    • Try to use equal conditions to access data, which canavoid the impact of gap locks on concurrent insertion(In fact, equal query will also Add gap lock) Do not apply for a lock level that exceeds the actual need

    • If it is not necessary, avoid using explicit locking when querying, because under the committed read and repeatable read isolation levels, MVCC has provided a reading mechanism without manual locking

    The above is the detailed content of What are MySQL's intent shared locks, intent exclusive locks and deadlocks?. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

    Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

    How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

    MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

    How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

    Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

    How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

    How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

    How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

    One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

    How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

    To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

    How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

    Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

    The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

    Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

    See all articles