


Detailed explanation of MySQL deadlock usage and detection and avoidance methods
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
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";
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:
[Err] 1213 - Deadlock found when trying to get lock; try restarting transaction
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.
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.
First of all, the SHow STATUS command includes some row lock information:
show status like 'innodb_row_lock_%';
lnnodb_row_lock_current_waits: The number of locks currently waiting for;
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; --当前出现的锁
select * from information_schema.INNODB_LOCK_WAITS; --锁等待的对应关系
更加详细的锁信息,开启标准监控和锁监控:
额外的监控肯定会消耗额外的性能
set GLOBAL innodb_status_output=ON; set GLOBAL innodb_status_output_locks=ON;
通过分析锁日志,找出持有锁的事务之后呢?
如果一个事务长时间持有锁不释放,可以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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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 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.

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.

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.

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.

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

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.
