Rechercher dans le manuel MySQL

15.7.5.1 An InnoDB Deadlock Example

The following example illustrates how an error can occur when a lock request would cause a deadlock. The example involves two clients, A and B.

First, client A creates a table containing one row, and then begins a transaction. Within the transaction, A obtains an S lock on the row by selecting it in share mode:

  1. mysql> CREATE TABLE t (i INT) ENGINE = InnoDB;
  2. Query OK, 0 rows affected (1.07 sec)
  3.  
  4. mysql> INSERT INTO t (i) VALUES(1);
  5. Query OK, 1 row affected (0.09 sec)
  6.  
  7. Query OK, 0 rows affected (0.00 sec)
  8.  
  9. mysql> SELECT * FROM t WHERE i = 1 FOR SHARE;
  10. +------+
  11. | i    |
  12. +------+
  13. |    1 |
  14. +------+

Next, client B begins a transaction and attempts to delete the row from the table:

  1. Query OK, 0 rows affected (0.00 sec)
  2.  
  3. mysql> DELETE FROM t WHERE i = 1;

The delete operation requires an X lock. The lock cannot be granted because it is incompatible with the S lock that client A holds, so the request goes on the queue of lock requests for the row and client B blocks.

Finally, client A also attempts to delete the row from the table:

  1. mysql> DELETE FROM t WHERE i = 1;
  2. ERROR 1213 (40001): Deadlock found when trying to get lock;
  3. try restarting transaction

Deadlock occurs here because client A needs an X lock to delete the row. However, that lock request cannot be granted because client B already has a request for an X lock and is waiting for client A to release its S lock. Nor can the S lock held by A be upgraded to an X lock because of the prior request by B for an X lock. As a result, InnoDB generates an error for one of the clients and releases its locks. The client returns this error:

  1. ERROR 1213 (40001): Deadlock found when trying to get lock;
  2. try restarting transaction

At that point, the lock request for the other client can be granted and it deletes the row from the table.


Find a PHP function

Document created the 26/06/2006, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/mysql-rf-innodb-deadlock-example.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.

References

  1. View the html document Language of the document:en Manuel MySQL : https://dev.mysql.com/

These references and links indicate documents consulted during the writing of this page, or which may provide additional information, but the authors of these sources can not be held responsible for the content of this page.
The author This site is solely responsible for the way in which the various concepts, and the freedoms that are taken with the reference works, are presented here. Remember that you must cross multiple source information to reduce the risk of errors.

Contents Haut