PHP uses file lock to solve high concurrency problem example

http://www.jb51.net/article/137359.htm

 

This article mainly introduces the use of file locks in PHP to solve high concurrency problems, and analyzes the use of PHP blocking mode and non-blocking mode file locks to solve high concurrency problems in combination with examples. Friends who need it can refer to the following

 

 

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 always 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 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
//连接数据库
$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 );
?>

If it takes time to connect to the database, there is a simple demo below, which can be understood more intuitively.

demo.php

 
<?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 );

demo2.php

 
<?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 );

Run two files at the same time, and then modify the locking mechanism in demo2, you can see the difference between blocking (waiting) mode and non-blocking (waiting) mode.

But this will cause the queue to be blocked. If 10 people write to the database in the same second, it will be blocked. The 10th person will wait for the first 9 to be executed before executing!

Guess you like

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