简体   繁体   English

如果几个客户在MySQL中选择,如何避免竞争条件?

[英]How to avoid race condition if several clients select in MySQL?

I have a task_id table which has two columns: 我有一个task_id表,它有两列:

`tid`:task id,
`state`:0:unfinished,1:processing,2:finished

It's easy if I use only one client(Perl script): fetch one unfinished task id,update it to processing , process it, and update it to finished in a loop. 如果我只使用一个客户端(Perl脚本)很容易:获取一个unfinished任务ID,将其更新为processing ,处理它,并将其更新为循环finished

But I'm planning to use several clients to do the task. 但我打算用几个客户来完成这项任务。 There is a chance that two clients fetch a record in the same time, how to avoid it? 两个客户端有可能在同一时间获取记录,如何避免它?

如果您的mysql表的引擎是INNODB,那么它会在更新表记录时锁定该特定行,以便其他请求不会与先前的更新冲突。

Have the update be something like: 更新是这样的:

update task_id set state=1 where tid=? and state=0;

then check if the update actually modified a record. 然后检查更新是否实际修改了记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM