This time I will bring you a detailed explanation of the steps for PHP to use file locks to solve high concurrency. What are the precautions for PHP to use file locks to solve high concurrency? The following is a practical case, let's take a look.
Create a new .txt file without writing anything in the file.[1]. Blocking (waiting) mode: (As long as other processes have locked the file, the current process will wait for other processes to unlock the file )
<?php //连接数据库 $con=mysqli_connect("192.168.2.186","root","root","test"); //查询商品数量是否大于0,大于0才能下单,并减少库存 $fp = fopen("lock.txt", "r"); //加锁 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');} //执行完成解锁 flock($fp,LOCK_UN); } //关闭文件 fclose($fp); unset($res); mysqli_close($con); ?>
[2]. Non-blocking (waiting) mode:(As long as other processes have locked the file, the current process will not It will wait for other processes to unlock the file and return directly)
<?php //连接数据库 $con=mysqli_connect("192.168.2.186","root","root","test"); //查询商品数量是否大于0,大于0才能下单,并减少库存 $fp = fopen("lock.txt", "r"); //加锁 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');} //执行完成解锁 flock($fp,LOCK_UN); } //关闭文件 fclose($fp); unset($res); mysqli_close($con); ?>
<?php $fp = fopen("file_lock.txt", "r"); // 加锁 if(flock($fp, LOCK_EX)) { sleep(10); echo 1; //执行完成解锁 flock($fp,LOCK_UN); } else { echo 2; } //关闭文件 fclose($fp);
<?php $fp = fopen("file_lock.txt", "r"); // 加锁(如果改成flock($fp, LOCK_EX | LOCK_NB),demo2.php会直接返回2,否则会等待demo.php执行完返回1) if(flock($fp, LOCK_EX)) { echo 1; } else { echo 2; } //关闭文件 fclose($fp);
Detailed explanation of the use of PHP decorator mode
Detailed explanation of the steps for PHP to dynamically obtain function parameters
The above is the detailed content of Detailed explanation of steps to solve high concurrency issues using PHP file locks. For more information, please follow other related articles on the PHP Chinese website!