Home > Article > Backend Development > Examples of using flock to write blocking and non-blocking files in PHP
Explanation on how php uses flock to block writing files and non-blocking writing files:
Blocking writing code: (All programs will wait for the last time The program will not be executed until it is finished and will time out in 30 seconds)
<?php$file = fopen("test.txt","w+"); $t1 = microtime(TRUE);if (flock($file,LOCK_EX)) { sleep(10); fwrite($file,"Write something"); flock($file,LOCK_UN); echo "Ok locking file!"; }else{ echo "Error locking file!"; } fclose($file); $t2 = microtime(TRUE);echo sprintf("%.6f",($t2-$t1));
Non-blocking writing code: ( As long as the file is occupied, Error locking file!) is displayed:
<?php$file = fopen("test.txt","a+"); $t1 = microtime(TRUE);if (flock($file,LOCK_EX|LOCK_NB)) { sleep(10); fwrite($file,"Write something"); flock($file,LOCK_UN); echo "Ok locking file!"; }else{ echo "Error locking file!"; } fclose($file); $t2 = microtime(TRUE);echo sprintf("%.6f",($t2-$t1));
The above is the detailed content of Examples of using flock to write blocking and non-blocking files in PHP. For more information, please follow other related articles on the PHP Chinese website!