Home  >  Article  >  Backend Development  >  Examples of using flock to write blocking and non-blocking files in PHP

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

巴扎黑
巴扎黑Original
2017-07-20 17:48:031833browse

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));

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));

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!

Statement:
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