質問

I'm having trouble getting a table to lock in MySQL. I've tried testing for concurrent requests by running two scripts at the same time on different browsers.

Script 1:

mysql_query("lock tables id_numbers write");

$sql = "select number from id_numbers";
$result = mysql_query($sql);

if ($record = mysql_fetch_array($result))
{
  $id = $record['number'];
}

sleep(30);

$id++;

$sql = "update id_numbers set number = '$id'";
$result = mysql_query($sql);

mysql_query("unlock tables");

Script 2:

$sql = "select number from id_numbers";
$result = mysql_query($sql);

if ($record = mysql_fetch_array($result))
{
  $id = $record['number'];
}

echo $id;

I start Script 1 first, then start Script 2. Theoretically, Script 2 should wait 30+ seconds until Script 1 unlocks the table, and then output the updated ID. But it immediately outputs the original ID, so the lock is obviously not taking effect. What could be going wrong?

BTW, I know I shouldn't still be using mysql_*, but I'm stuck with it for now.

EDIT: I've discovered that the lock does happen on the live site, but not on my dev site. They are both on shared hosts, so I'm assuming there's some setting that's different between the two. Any idea what that could be?

正しい解決策はありません

他のヒント

Using the code you have here, I get exactly the behavior you expect: script 2 will block until script 1 issues the unlock tables.

Your problem must lie elsewhere. Things to check:

  1. Does the table actually exist on the database? (Check your mysql_query() return values and use mysql_error() if you get any FALSE returns.)
  2. Are both scripts connecting to the same database?
  3. Are you sure the table is not a temporary (thus connection-local) table?
  4. Could script 1's mysql connection (or the script itself) be timing out during the sleep(30), thus releasing the lock earlier than you expect?
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top