当前位置:主页 > 软件编程 > PHP代码 >

php使用flock阻塞写入文件和非阻塞写入文件的实例讲解

时间:2020-10-23 16:05:12 | 栏目:PHP代码 | 点击:

阻塞写入代码:(所有程序会等待上次程序执行结束才会执行,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)); 

您可能感兴趣的文章:

相关文章