php使用flock阻塞写入文件和非阻塞写入文件的实例讲解
阻塞写入代码:(所有程序会等待上次程序执行结束才会执行,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));
相关推荐
wangshaoM00 2017-05-26
qianfengphp 2017-12-29
SmartPhone 2018-02-15
qifei 2013-09-16
iamlazyphper 2017-08-07
zhengkai00 2009-01-16
phpcrazy 2014-02-28
firefaith 2019-04-05
大牛牛 2019-04-03
icesschen 2009-03-04
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-28
PHP100 2019-03-27