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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    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)

    How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

    You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

    MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

    MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

    How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

    Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

    MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

    MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

    Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

    MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

    Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

    Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

    How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

    The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

    How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

    Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

    See all articles