note 95257 added to function.flock

From: Date: Mon, 21 Dec 2009 21:47:08 +0000
Subject: note 95257 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-164250@lists.php.net to get a copy of this message
Actually, there is no use of the while loop with the usleep. My testing has revealed the following: <?php //some code here flock($file_handle, LOCK_EX) // <- Your code will pause here untill you get the lock for indefinite amount of time or till your script times out //some code here ?> This will actually check for the lock without pausing and then it will sleep: <?php //code here while (!flock($file_handle, LOCK_EX | LOCK_NB)) { //Lock not acquired, try again in: usleep(round(rand(0, 100)*1000)) //0-100 miliseconds } //lock acquired //rest of the code ?> The problem is, if you have a busy site and a lots of locking, the while loop may not acquire the lock for some time. Locking without LOCK_NB is much more persistent and it will wait for the lock for as long as it takes. It is almose guaranteed that the file will be locked, unless the script times out or something. Consider these two scripts: 1st one is ran, and the second one is ran 5 seconds after the first. <?php //1st script $file_handle = fopen('file.test', 'r+'); flock($file_handle, LOCK_EX); //lock the file sleep(10); //sleep 10 seconds fclose($file_handle); //close and unlock the file ?> <?php //2nd script $file_handle = fopen('file.test', 'r+'); flock($file_handle, LOCK_EX); //lock the file fclose($file_handle); //close and unlock the file ?> If you run 1st and then the 2nd script,the 2nd script will wait untill the 1st has finished. As soon as the first script finishes, the second one will acquire the lock and finish the execution. If you use flock($file_handle, LOCK_EX | LOCK_NB) in the 2nd script while the 1st script is running, it would finish execution immediately and you would not get the lock. ---- Server IP: 69.147.83.197 Probable Submitter: 93.86.126.253 ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- https://master.php.net/note/edit/95257 Del: integrated -- https://master.php.net/note/delete/95257/integrated Del: useless -- https://master.php.net/note/delete/95257/useless Del: bad code -- https://master.php.net/note/delete/95257/bad+code Del: spam -- https://master.php.net/note/delete/95257/spam Del: non-english -- https://master.php.net/note/delete/95257/non-english Del: in docs -- https://master.php.net/note/delete/95257/in+docs Del: other reasons-- https://master.php.net/note/delete/95257 Reject -- https://master.php.net/note/reject/95257 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#164250) next »