This time to bring you tphp use file lock to solve high concurrency problem, php use file lock to solve high concurrency problems of attention to what, the following is the actual case, take a look.
Create a new. txt file without writing anything in the file.
"One." block (Wait) mode : (as long as other processes have locked files, the current process waits for other processes to unlock the files)
<?php
Connecting to a database
$con =mysqli_connect ("192.168.2.186", "root", "root", "test");
Check whether the number of items is greater than 0, greater than 0 to order, and reduce inventory
$fp = fopen ("Lock.txt", "R");
Locking
if (Flock ($FP, LOCK_EX))
if ($res [' total ']>0] {mysqli_query ($con, ' UPDATE shop SET total=total-1 WHERE id=1 ');} Perform the completion of the unlock
Flock ($FP, lock_un);
}
Close File
Fclose ($FP);
Unset ($res);
Mysqli_close ($con);
?>
"Two". non-blocking (wait) mode : (the current process does not wait for the other process to unlock the file, as long as other processes have already locked the file)
<?php
Connecting to a database
$con =mysqli_connect ("192.168.2.186", "root", "root", "test");
Check whether the number of items is greater than 0, greater than 0 to order, and reduce inventory
$fp = fopen ("Lock.txt", "R");
Locking 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 ');}
Perform the completion of the unlock
Flock ($FP, lock_un);
}//closing files
Fclose ($FP);
Unset ($res);
Mysqli_close ($con);
?>
If the connection database fee time, there is a simple small demo, you can more intuitive understanding.
demo.php <?php$fp = fopen ("File_lock.txt", "R"); Locking if (Flock ($FP, lock_ex)) { sleep]; echo 1; Execution completion unlock flock ($fp, lock_un);} else { echo 2;} Close file fclose ($fp);d emo2.php<?php$fp = fopen ("File_lock.txt", "R");//Locking (if changed to flock ($FP, LOCK_EX | LOCK_NB), demo2.php will return 2 directly, otherwise it will wait for demo.php execution to return 1) if (Flock ($FP, lock_ex)) { echo 1;} else { echo 2;} Close file fclose ($FP);
Run two files at the same time, and then modify the lock mechanism in the DEMO2, you can see the blocking (wait) mode and non-blocking (wait) mode
The difference.
But this will cause the queue congestion, if 10 people write to the database in the same second, it is blocked, the 10th person will wait for the first 9 to execute before execution!