Comparison of blocking and non-blocking methods of writing files using flock in PHP

小云云
Release: 2023-03-20 06:28:01
Original
1611 people have browsed it

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));
Copy after login

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));
Copy after login

Related recommendations:

In-depth understanding of coroutines and blocking in php

Detailed explanation of classic and non-blocking

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!