php file lock

[1]. Blocking (waiting) mode: (As long as other processes have locked the file, the current process will always wait for other processes to unlock the file)

<?php
//Connect to the database
$con=mysqli_connect("192.168.2.186","root","root","test");

//Check if the quantity of the item is greater than 0, if it is greater than 0, you can place an order and reduce the inventory

$fp = fopen("lock.txt", "r");
// lock
if(flock($fp,LOCK_EX))
{
	$res=mysqli_fetch_assoc(mysqli_query($con,'SELECT total FROM shop WHERE id=1 LIMIT 1'));
	if($res['total']>0){mysqli_query($con,'UPDATE shop SET total=total-1  WHERE id=1');}
	// execute complete unlock
	flock($fp,LOCK_UN);
}
//close the file
fclose($fp);
unset($res);
mysqli_close($con);
?>

  

[2]. Non-blocking (waiting) mode: (As long as there are other processes that have locked the file, the current process will not wait for other processes to unlock the file and return directly)

<?php
//Connect to the database
$con=mysqli_connect("192.168.2.186","root","root","test");

//Check if the quantity of the item is greater than 0, if it is greater than 0, you can place an order and reduce the inventory

$fp = fopen("lock.txt", "r");
// lock
if(flock($fp,LOCK_EX | LOCK_NB))
{
	$res=mysqli_fetch_assoc(mysqli_query($con,'SELECT total FROM shop WHERE id=1 LIMIT 1'));
	if($res['total']>0){mysqli_query($con,'UPDATE shop SET total=total-1  WHERE id=1');}
	// execute complete unlock
	flock($fp,LOCK_UN);
}
//close the file
fclose($fp);
unset($res);
mysqli_close($con);
?>

  Summary: If the amount of concurrency is not large, it is OK. If the amount of concurrency is large, the performance is relatively low, and when data is inserted at the same time, the data request will fail.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325211013&siteId=291194637