我正在尝试使用MYSQL锁在php中构建一个互斥锁。
每个用户都有一个进程,我希望每个进程一次执行一次。
我希望如果用户“my_user”的一个进程检查存在“my_user”的其他进程,则新进程采用其他方式,例如一段代码报告该用户的进程已在执行。< / p>
我有这个测试代码,我看到GET_LOCK函数在第二个实例中等待超过1秒,为什么?
//name of the lock
$user = "my_user";
//calling get_lock with 1 second as timeout
$i_sql = "SELECT GET_LOCK('$user', 1)";
if($debug) file_put_contents($logfile, "$i_sql \r\n", FILE_APPEND);
$result = mysqli_query($con, $i_sql);
if (!$result) {
echo "Could not successfully run query ($i_sql) from DB: " . mysql_error();
exit;
}
echo "Adquired ".date('Y-m-d H:i:s')."<br>";
$row = mysqli_fetch_array($result);
print_r($row);
echo "<br>";
$count = 0;
//stay here 10 seconds
while($count < 2){
sleep(5);
$count++;
}
//release the lock
$i_sql = "SELECT RELEASE_LOCK('$user')";
if($debug) file_put_contents($logfile, "$i_sql \r\n", FILE_APPEND);
$result = mysqli_query($con, $i_sql);
if (!$result) {
echo "Could not successfully run query ($i_sql) from DB: " . mysql_error();
exit;
}
echo "Release ".date('Y-m-d H:i:s')."<br>";
mysqli_close($con);
unset($con);
输出:
流程1 于10:00:07启动:
Adquired 2013-07-08 10:00:08
Array ( [0] => 1 [GET_LOCK('my_user', 1)] => 1 )
Release 2013-07-08 10:00:18
流程2 于10:00:08发布:
Adquired 2013-07-08 10:00:18
Array ( [0] => 1 [GET_LOCK('my_user', 1)] => 1 )
Release 2013-07-08 10:00:28