Home  >  Article  >  Backend Development  >  Detailed explanation of steps to solve high concurrency issues using PHP file locks

Detailed explanation of steps to solve high concurrency issues using PHP file locks

php中世界最好的语言
php中世界最好的语言Original
2018-05-17 13:47:501883browse

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 )

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)

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 connecting to the database takes time, there is a simple demo below for a more intuitive understanding.

demo.php

demo2.php

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

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

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn