start transaction; -6ren">
gpt4 book ai didi

MySQL InnoDB "SELECT FOR UPDATE"- 跳过锁定等效

转载 作者:可可西里 更新时间:2023-11-01 07:20:00 25 4
gpt4 key购买 nike

当我们在 MySQL 中使用 InnoDB 表进行“SELECT FOR UPDATE”时,有什么方法可以跳过“锁定的行”吗?

例如:航站楼 t1

mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> select id from mytable ORDER BY id ASC limit 5 for update;
+-------+
| id |
+-------+
| 1 |
| 15 |
| 30217 |
| 30218 |
| 30643 |
+-------+
5 rows in set (0.00 sec)

mysql>

同时,终端t2:

mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> select id from mytable where id>30643 order by id asc limit 2 for update;
+-------+
| id |
+-------+
| 30939 |
| 31211 |
+-------+
2 rows in set (0.01 sec)

mysql> select id from mytable order by id asc limit 5 for update;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql>

因此,如果我启动一个查询强制它选择其他行,那没问题。

但是有没有办法跳过锁定的行呢?

我猜这应该是并发过程中的一个冗余问题,但我没有找到任何解决方案。


编辑:实际上,我的不同并发进程正在做一些看似非常简单的事情:

  1. 取第一行(不包含特定标志 - 例如:“WHERE myflag_inUse!=1”)。

  2. 获得“选择更新”的结果后,我更新标志并提交行。

所以我只想选择尚未锁定的行以及 myflag_inUse!=1...


以下链接可以帮助我理解超时的原因,但不能帮助我理解如何避免超时:

MySQL 'select for update' behaviour


mysql> SHOW VARIABLES LIKE "%version%";
+-------------------------+-------------------------+
| Variable_name | Value |
+-------------------------+-------------------------+
| innodb_version | 5.5.46 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.46-0ubuntu0.14.04.2 |
| version_comment | (Ubuntu) |
| version_compile_machine | x86_64 |
| version_compile_os | debian-linux-gnu |
+-------------------------+-------------------------+
7 rows in set (0.00 sec)

最佳答案

MySQL 8.0 引入了对SKIP LOCKEDNO WAIT 的支持。

SKIP LOCKED 对于实现作业队列(也称为批处理队列)很有用,这样您就可以跳过已被并发事务锁定的锁。

NO WAIT 有助于避免等待并发事务释放我们也有兴趣锁定的锁。

如果没有 NO WAIT,我们要么必须等到锁被释放(在当前持有锁的事务提交或释放时),要么锁获取超时。 NO WAIT 充当值为 0 的锁定超时。

有关SKIP LOCK的更多详细信息和 NO WAIT

关于MySQL InnoDB "SELECT FOR UPDATE"- 跳过锁定等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33411620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com