使用下面的代碼來防止競爭條件安全嗎? (key
和status
領域和mysql_affected_rows用於實現鎖定)使用mysql_affected_row來防止競爭條件
$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
這似乎是正確的,唯一的錯誤可能是如果'id'不是表中的PRIMARY/UNIQUE鍵。另外,您需要在所有情況下都將'UPDATING'作爲字符串。 – hjpotter92