gpt4 book ai didi

mysql - 更新状态的行锁

转载 作者:行者123 更新时间:2023-11-29 01:46:46 25 4
gpt4 key购买 nike

我有一个状态为('toprocess'、'processing'、'done')的“要执行的命令”表

我有几个实例 (amazon ec2),其中有一个守护进程要求“要执行的命令”。

守护进程请求状态为“toprocess”的行,然后进行处理,并在每个循环结束时将状态更改为“done”。

问题是,在开始该循环之前,我需要将所有行“toprocess”更改为状态“processing”,这样其他实例就不会采用相同的行,从而避免冲突。

我读过关于 innodb 行锁的内容,但我不是很了解它们......

SELECT * from commands where status = 'toprocess'然后我需要获取这些结果的 ID,并将状态更新为“正在处理”,锁定这些行直到它们被更新。

我该怎么做?

谢谢

最佳答案

您将使用一个事务,并使用 FOR UPDATE 读取数据,这将阻止其他选择,包括对被选择的行的 FOR UPDATE

begin transaction;
select * from commands where status = 'toprocess' for update;
for each row in the result:
add the data to an array/list for processing later.
update commands set status='processing' where id = row.id;

commit;

process all the data

阅读一些关于 FOR UPDATE 的内容和 InnoDB isolation levels .

关于mysql - 更新状态的行锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4971860/

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