note 60184 added to function.flock

From: Date: Thu, 29 Dec 2005 04:12:21 +0000
Subject: note 60184 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-100894@lists.php.net to get a copy of this message
Hello guys, I want to shear one good trick, it was no invented by me but it is very useful with flock. This technology was used by team who invent Ethernet as my tutor Pitter Timothy teach me. I want to say thank you. If you have a lot of scripts about 1000 which possible try to write something in file you need to lock file before starting writing. So you should use something like this: $fp = fopen($logFileName, 'a'); $canWrite = false; //Waiting until file will be locked for writing while (!$canWrite) { $canWrite = flock($fp, LOCK_EX); } //file was locked so now we can store information fwrite($fp, $toSave); fclose($fp); but during testing I have find out what some times script have to many collisions, and during 10 seconds can not write anything. It happened because some scripts try simultaneously. If file was busy they all will wait same time. So I use the same technology like guys who invent first simple Ethernet use in case of package collision. I put random millisecond sleep. You can not imagine but script start working 3 times quicker! $fp = fopen($logFileName, 'a'); $canWrite = false; //Waiting until file will be locked for writing while (!$canWrite) { $canWrite = flock($fp, LOCK_EX); //Sleep for 0 - 2000 miliseconds, to avoid colision $miliSeconds = rand(0, 20); //1 u = 100 miliseconds usleep(round($miliSeconds*100000)); } //file was locked so now we can store information fwrite($fp, $toSave); fclose($fp); By the way I have no idea which diapason is better, but 0 – 1000 is not enough. Hope it will help somebody Best regards in your projects Vitali Simsive ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+60184 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60184&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+60184&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#100894) next »