时间:2021-07-01 10:21:17 帮助过:3人阅读
阻塞写入代码:(所有程序会等待上次程序执行结束才会执行,30秒会超时)
<?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));
非阻塞写入代码:(只要文件被占用,则显示Error locking file!)
<?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));
相关推荐:
php中关于协程与阻塞的深入理解
经典型和非阻塞型<script>标签用法实例详解
详解同步、异步、阻塞和非阻塞的不同之处
以上就是php使用flock阻塞和非阻塞写入文件方法对比的详细内容,更多请关注Gxl网其它相关文章!