gpt4 book ai didi

mysql - 选择...更新会导致锁定

转载 作者:行者123 更新时间:2023-11-29 14:15:40 24 4
gpt4 key购买 nike

当用户注册我们的服务时,我想从多个 solr 核心(一种资源)中分配一个。一个核心独占给一位用户(例如!)。我想使用select ...for update来确保并发注册看到(并使用)不同的行

东西适用于第一次注册交易;我们得到了允许使用的行。但对于第二个(以后),会发生超过锁定等待超时当我想要下一行时。

为什么 MySQL 会抛出这个错误?

从 1 号航站楼出发:

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

mysql> select * from SolrCoresPreallocated order by id limit 1 for update;
+----+-------------+-----+-----+
| id | used_status | sid | cid |
+----+-------------+-----+-----+
| 1 | 0 | 0 | 400 |
+----+-------------+-----+-----+
1 row in set (0.00 sec)

在 2 号航站楼:

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

mysql> select * from SolrCoresPreallocated order by id limit 1 for update;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> rollback;
Query OK, 0 rows affected (0.00 sec)

我其实想看看:

mysql> select * from SolrCoresPreallocated order by id limit 1 for update;
+----+-------------+-----+-----+
| id | used_status | sid | cid |
+----+-------------+-----+-----+
| 2 | 0 | 0 | 401 |
+----+-------------+-----+-----+
1 row in set (0.00 sec)
<小时/>

我的数据是:

mysql> select * from SolrCoresPreallocated;
+----+-------------+-----+-----+
| id | used_status | sid | cid |
+----+-------------+-----+-----+
| 1 | 0 | 0 | 400 |
| 2 | 0 | 0 | 401 |
| 3 | 0 | 0 | 402 |
| 4 | 0 | 0 | 403 |
| 5 | 0 | 0 | 404 |
| 6 | 0 | 0 | 405 |
+----+-------------+-----+-----+
6 rows in set (0.00 sec)

我在以下位置描述了我的问题:Different transactions must guarantedly select different items; avoid contentions

最佳答案

这个查询实际上总是请求并锁定同一行,无论哪个 MySQL 连接运行它。

select * from SolrCoresPreallocated order by id limit 1 for update;

锁定的行不会以某种方式神奇地从 future 的查询中排除。他们只是被锁了。这就是你所看到的问题;您的所有操作都锁定同一行。

如果你能做这样的事情(警告:伪代码;警告:我不理解你的模式)它很可能会工作得更好

 begin;

update SolrCoresPreallocated
set allocated = (this customer id)
where allocated = 0
limit 1;

(check result; if no rows were modified you ran out of allocated=0 rows.)

select * from SolrCoresPreallocated where allocated = (this customer id);

commit;

关于mysql - 选择...更新会导致锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12745938/

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