Home > Backend Development > PHP Tutorial > Application of lock mechanism in PHP

Application of lock mechanism in PHP

不言
Release: 2023-04-03 13:22:02
Original
2455 people have browsed it

This article introduces you to the article about the application of the lock mechanism in PHP. It has a good reference value. I hope it can help friends in need.

Application environment

Resolve the situation of high concurrency and negative inventory

Blocking mode

If other processes have locked the file, the current process will wait forever Continue execution after other processes unlock the file

flock($fp, LOCK_EX) //File lock

Non-blocking mode

If other processes have been added Lock the file, the current process will not wait for other processes to unlock the file, and return directly, that is, directly ignore the locking code and go to the block to close the file

flock($fp,LOCK_EX | LOCK_NB) //File lock

Code

flock($fp, LOCK_EX) and flock($fp,LOCK_EX | LOCK_NB) Replace Just click it, everything else is the same

<?php
$fp = fopen(&#39;lock.txt&#39;, &#39;r&#39;);
if( flock($fp, LOCK_EX) ){      // flock($fp,LOCK_EX | LOCK_NB)
    $info = D()->query('SELECT surplus_total_num FROM tb_product WHERE id=1 LIMIT 1');
    if( $info['surplus_total_num'] > 0 ){
        D()->execute('UPDATE tb_product SET surplus_total_num = surplus_total_num - 1  WHERE id=1');
        $isSurplusProduct = 1;
    }else{
        $isSurplusProduct = 0;
    }
    flock($fp, LOCK_UN);
}
fclose($fp);

if( !$isSurplusProduct ) exit('已经没有产品了');
Copy after login

Concurrency test

Check whether the database inventory is consistent and remains 0 ab parameters: -c: number of concurrencies; -n: total number of requests

ab -c 20 -n 1000 http://www.test.com/test.php

Related recommendations:

phpHow to achieve equal proportions Code for compressing images

Example of writing shell command from php command line

The above is the detailed content of Application of lock mechanism in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template