Home >Backend Development >PHP Tutorial >Application of lock mechanism in PHP
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.
Resolve the situation of high concurrency and negative inventory
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
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
flock($fp, LOCK_EX)
and flock($fp,LOCK_EX | LOCK_NB)
Replace Just click it, everything else is the same
<?php $fp = fopen('lock.txt', 'r'); 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('已经没有产品了');
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!