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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles