Table of Contents
Lock release and blocking
Occurrence and detection of deadlock
First of all, the SHow STATUS command includes some row lock information:
死锁的避免
Home Database Mysql Tutorial Detailed explanation of MySQL deadlock usage and detection and avoidance methods

Detailed explanation of MySQL deadlock usage and detection and avoidance methods

Sep 09, 2022 pm 01:43 PM
mysql

Recommended study: mysql video tutorial

When we use locks, there is a problem that needs to be paid attention to and avoided. We know that exclusive locks have mutually exclusive characteristics. When a transaction or a thread holds a lock, it will prevent other threads from acquiring the lock. This will cause blocking waiting. If you wait in a loop, it may cause a deadlock.

We need to analyze this problem from several aspects. One is why the lock is not released, the second is what to do if it is blocked, and the third is how deadlock occurs and how to avoid it.

Lock release and blocking

Review: When will the lock be released?
Transaction ends (commit, rollback);
The client connection is disconnected.

If a transaction has not released the lock, how long will other transactions be blocked? Will they wait forever?
If so, when concurrent access is relatively high, if a large number of transactions are blocked due to Failure to obtain the required lock immediately and hanging will occupy a lot of computer resources, cause serious performance problems, and even drag across the database.

Are you afraid of this mistake online?

[Err] 1205 - Lock wait timeout exceeded; try restarting transaction
Copy after login

MySQL has a parameter to control the waiting time to acquire the lock, the default is 50 seconds.

show VARIABLES like "innodb_lock_wait_timeout";
Copy after login

For deadlock, no matter how long you wait, you cannot obtain the lock. In this case, do you need to wait 50 seconds? Isn't that 50 seconds wasted in vain?

Occurrence and detection of deadlock

Demonstration, open two sessions:

Facilitates the withdrawal of the timeline, pictures are used here, those who are interested can follow Imitate it

Chestnut one:

## Chestnut two:

In the first transaction, a deadlock was detected and exited immediately. The second transaction obtained the lock without waiting for 50 seconds:

[Err] 1213 - Deadlock found when trying to get lock; try restarting transaction
Copy after login

Why can it be detected directly? This is because certain conditions need to be met for the occurrence of deadlock. For us programmers, having clear conditions means being able to determine. Therefore, when a deadlock occurs, InnoDB can generally automatically detect it through the algorithm (wait-for graph). arrive.

So what conditions need to be met for deadlock? The conditions for deadlock to occur, because the lock itself is mutually exclusive:

    (1) At the same time, only There is a transaction holding this lock;
  • (2) Other transactions need to release the lock before this transaction can acquire the lock, and cannot forcibly deprive it;
  • (3) When multiple When a transaction forms a waiting loop, a deadlock occurs.
The barber shop has two directors. There is Teacher Tony who is responsible for cutting hair, and Teacher Kelvin who is responsible for washing hair. Teacher Tony cannot cut the hair of two people at the same time. This is called mutual exclusion.

When Tony is cutting someone's hair, you can't ask him to stop and cut your hair. This is called Cannot be taken away by force

.

If Tony’s client says to Kelvin: How can I cut my hair if you don’t wash it for me? Kelvin’s client says to Tony: How can I wash my hair if you don’t cut my hair? This is called forming a waiting loop. .
In fact, there are many situations where deadlock occurs, but they all meet the above three conditions. This is also why table locks will not cause deadlock, because the resources of table locks are acquired all at once
.
If the lock has not been released, it may cause a lot of blocking or deadlock, resulting in a decrease in system throughput. At this time, you need to check which transactions hold the lock.

View lock information (log)

First of all, the SHow STATUS command includes some row lock information:

show status like 'innodb_row_lock_%';
Copy after login

lnnodb_row_lock_current_waits: The number of locks currently waiting for;

lnnodb_row_lock_time: The total length of time from system startup to the current lock, in ms;
Innodb_row_lock_time_avg: The average time spent waiting each time;

Innodb_row_lock_time_max: The longest wait time from system startup to now;
lnnodb_row_lock_waits: The total number of waits from system startup to now.


SHOW command is a summary information. InnoDB also provides three tables to analyze transactions and locks:

select * from information_schema.INNODB_TRX; --当前运行的所有事务﹐还有具体的语句
Copy after login

select* from information_schema.INNODB_LOCKS; --当前出现的锁
Copy after login

select * from information_schema.INNODB_LOCK_WAITS; --锁等待的对应关系
Copy after login

更加详细的锁信息,开启标准监控和锁监控:

额外的监控肯定会消耗额外的性能

set GLOBAL innodb_status_output=ON;
set GLOBAL innodb_status_output_locks=ON;
Copy after login

通过分析锁日志,找出持有锁的事务之后呢?
如果一个事务长时间持有锁不释放,可以kill事务对应的线程ID,也就是INNODB_TRX表中的trx_mysql_thread_id,例如执行kill 4,kill 7, kill 8。
当然,死锁的问题不能每次都靠kill线程来解决,这是治标不治本的行为。我们应该尽量在应用端,也就是在编码的过程中避免。
有哪些可以避免死锁的方法呢?

死锁的避免

  • 1、在程序中,操作多张表时,尽量以相同的顺序来访问(避免形成等待环路)
  • 2、批量操作单张表数据的时候,先对数据进行排序(避免形成等待环路);
  • 3、申请足够级别的锁,如果要操作数据,就申请排它锁;
  • 4、尽量使用索引访问数据,避免没有where条件的操作,避免锁表;
  • 5、如果可以,大事务化成小事务;
  • 6、使用等值查询而不是范围查询查询数据,命中记录,避免间隙锁对并发的影响。

推荐学习:mysql视频教程

The above is the detailed content of Detailed explanation of MySQL deadlock usage and detection and avoidance methods. 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 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