使用以下代码来防止争用条件安全吗?(key和status字段以及mysql_affected_rows用于实现锁定)
$mres = mysql_query("SELECT `values`, `key`, `status`
FROM `test`
WHERE `id` = 1");
$row = mysql_fetch_array($mres);
if($row['status'] != UPDATING) {
$mres = mysql_query("UPDATE `test` SET
`status` = UPDATING,
`key` = `key` + 1
WHERE `id` = 1 AND `key` = ".$row['key']);
if($mres && mysql_affected_rows()) {
//update here safely and then...
mysql_query("UPDATE `test` SET
`status` = NOT_UPDATING,
`key` = `key` + 1
WHERE `id` = 1");
}
}我的测试显示,要么它不安全,要么我应该在代码中搜索隐藏得很好的错误。表为MyISAM
发布于 2012-06-23 04:35:15
在检索值之前,您应该首先“获取锁”。否则,它们可能会在您获得锁之前更改。
$mres = mysql_query("UPDATE `test` SET
`status` = 'UPDATING'
WHERE `id` = 1 AND `status` = 'NOT_UPDATING'");
if ($mres && mysql_affected_rows()) {
// got the lock
// now select and update
}id最好是数据库中的唯一字段,否则事情可能会表现得非常奇怪'UPDATING'和'NOT_UPDATING'在您的代码中,您还应该检查$row['status']是否具有有意义的值(如果它是false/null呢?)在与php常量UPDATING发布于 2012-06-23 05:13:27
您可以在MySql中检查GET_LOCK和RELEASE_LOCK函数来模拟行锁。
http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_get-lock
使用这种方法,您不需要更新行。同样,对于mysql_affected_rows(),如果出现问题,您可能会始终锁定行(例如,如果您在释放行之前通过将其状态更新为NOT_UPDATING来编写crash脚本)。当连接终止时,授予GET_LOCK的锁将自动释放。
https://stackoverflow.com/questions/11163359
复制相似问题