This article mainly shares with you a comparison of PHP's blocking and non-blocking methods of writing files using flock. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.
Blocking writing code: (All programs will wait for the last program execution to end before executing, 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 If 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));
Related recommendations:
In-depth understanding of coroutines and blocking in php
Detailed explanation of classic and non-blocking