数据库
首页 > 数据库> > mysql – 当我选择多行FOR UPDATE时,我可以死锁吗?

mysql – 当我选择多行FOR UPDATE时,我可以死锁吗?

作者:互联网

MySQL InnoDB中,假设我有一个表,两个线程都执行“SELECT … FOR UPDATE”.假设两个SELECT语句最终选择多行,例如它们最终都选择了行R42和R99.这可能会陷入僵局吗?

我正在考虑这种情况:第一个线程试图锁定R42然后R99,第二个线程试图锁定R99然后锁定R42.如果我运气不好,两个线程就会陷入僵局.

我读了MySQL Glossary for “deadlock”

A deadlock can occur when the transactions lock rows in multiple tables (through statements such as UPDATE or SELECT … FOR UPDATE), but in the opposite order. …

To reduce the possibility of deadlocks, … create indexes on the columns used in SELECT … FOR UPDATE and UPDATE … WHERE statements.

这暗示在我的情况下(单表)我不会死锁,也许是因为MySQL自动尝试按主键的顺序锁定行,但我想确定,我找不到合适的位置文档,告诉我究竟发生了什么.

解决方法:

来自MySQL文档

InnoDB uses automatic row-level locking. You can get deadlocks even in the case of 
transactions that just insert or delete a single row. That is because these operations    
are not really “atomic”; they automatically set locks on the (possibly several) index 
records of the row inserted or deleted.

http://dev.mysql.com/doc/refman/5.1/en/innodb-deadlocks.html

因此,通常情况下,死锁并不是致命的,您只需要再次尝试,或添加适当的索引,以便扫描更少的行,从而锁定更少的行.

标签:mysql,database-deadlocks
来源: https://codeday.me/bug/20190709/1414981.html