Actually, there is no use of the while loop with the usleep. My testing has revealed the following:
<?php
flock($file_handle, LOCK_EX) ?>
This will actually check for the lock without pausing and then it will sleep:
<?php
while (!flock($file_handle, LOCK_EX | LOCK_NB)) {
usleep(round(rand(0, 100)*1000)) }
?>
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
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); sleep(10); fclose($file_handle); ?>
<?php
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); fclose($file_handle); ?>
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.