Examples of using flock to write blocking and non-blocking files in PHP

巴扎黑
Release: 2023-03-13 21:00:02
Original
1832 people have browsed it

Explanation on how php uses flock to block writing files and non-blocking writing files:

Blocking writing code: (All programs will wait for the last time The program will not be executed until it is finished 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

Code School php

Non-blocking writing code: ( As long as the file is 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

The above is the detailed content of Examples of using flock to write blocking and non-blocking files in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template