note 109175 deleted from function.flock by danbrown
| From: | danbrown@php.net | Date: | Tue, 26 Jun 2012 13:44:37 +0000 |
| Subject: | note 109175 deleted from function.flock by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188813@lists.php.net to get a copy of this message | ||
Note Submitter: listofproxy at listofproxy dot net
----
Hello,
There is couple of reasons why EVERY software developer should avoid its usage if it is possible. My
own server was crashed couple of times because of flock (including hours of down time). So you have
to think twice before you will decide to use it.
After a while I have found the problematic situations. For my surprise it was not just badly written
PHP scripts, it was some unclear bugs in FreeBSD. In some case, when more than 20 requests per
second try to do exclusive flock on the same file, the scripts stuck ;) and they were using 100% of
CPU (only Apacheâs reboot or manual kill could stop them).
Soon after I have found nice solution (thanks arne at bukkie dot nl for good suggestion). I want to
share it with you:
<?php
// waiting until file will be locked for writing (1000 milliseconds as timeout)
if ($fp = fopen($fileName, 'a')) {
$startTime = microtime();
do {
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime()-$startTime) < 1000));
//file was locked so now we can store information
if ($canWrite) {
fwrite($fp, $dataToSave);
}
fclose($fp);
}?>
I have added simple timeout value for flock. Case flock was not obtained within N seconds - writing
will be skipped, instead of waiting and causing serverâs high CPU load.
With best regards
Owner of http://listofproxy.net