简体   繁体   English

MySQL MyISAM竞争条件

[英]MySQL MyISAM race condition

The function has next structure: 该函数具有下一个结构:

$q = 'LOCK TABLES table1 WRITE;';
mysql_query($q);    
$q = 'select id from table1 where is_delete = 0 limit 1;';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
$q = 'UNLOCK TABLES;';
mysql_query($q);

I locking all tables, but queries run parallel. 我锁定了所有表,但查询并行运行。 How fix this? 如何解决?

Check whether you're getting any MySQL errors on the LOCK TABLES query: 检查您是否在LOCK TABLES查询中遇到任何MySQL错误:

$q = 'LOCK TABLES table1 WRITE';
$r = mysql_query($q) or die(mysql_error());    

However, if this is all you are doing, you can also simply write: 但是,如果这是在做什么,你也可以简单地写:

UPDATE `table1 SET `is_delete` = 1 WHERE `is_delete` = 0 LIMIT 1

which does not require any locks at all. 根本不需要任何锁。 Of course, this will only work if the data from your first query is not being processed in any way, and if it doesn't really matter which row you are updating, as long as it's one in which is_delete is set to 0. This is what the code you posted does, too, but it's not immediately obvious to me what you would want to use this code for :) 当然,只有在第一个查询中的数据没有以任何方式处理,并且只要更新is_delete设置为0的is_delete行与更新的行无关紧要时,此方法is_delete也是您发布的代码的功能,但是对我来说,您要使用此代码的目的不是立即显而易见的:)

More generally, if you are using the default InnoDB storage engine for your MySQL table, you may want to look into SELECT ... FOR UPDATE: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html 更一般而言,如果您对MySQL表使用默认的InnoDB存储引擎,则可能需要查看SELECT ... FOR UPDATE: http : //dev.mysql.com/doc/refman/5.0/en/innodb- locking-reads.html

You could write: 您可以这样写:

$q = 'select id from table1 where is_delete = 0 limit 1 for update';
$res = mysql_fetch_assoc(mysql_query($q));

if($res) {
   $q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
   mysql_query($q);
}

See also: http://www.mysqlperformanceblog.com/2006/08/06/select-lock-in-share-mode-and-for-update/ 另请参见: http : //www.mysqlperformanceblog.com/2006/08/06/select-lock-in-share-mode-and-for-update/

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

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