public static function do_flock($fp, $lock, $timeout_ms = 384)
    {
        $l = flock($fp, $lock);
        if (!$l && ($lock & LOCK_UN) != LOCK_UN) {
            $st = microtime(true);
            $m  = min(1e3, $timeout_ms * 1e3);
            $n  = min(64e3, $timeout_ms * 1e3);
            if ($m == $n) {
                $m = ($n >> 1) + 1;
            }

            $timeout_ms = (float) $timeout_ms / 1000;
            // If lock not obtained sleep for 0 - 64 milliseconds, to avoid collision and CPU load
            do {
                usleep($t = rand($m, $n));
                $l = flock($fp, $lock);
            } while (!$l && (microtime(true) - $st) < $timeout_ms);
        }
        return $l;
    }
public static function do_flock($fp, $lock, $timeout_ms = 384)
    {
        $l = flock($fp, $lock);
        if (!$l && ($lock & LOCK_UN) != LOCK_UN) {
            $st = microtime(true);
            $m  = min(1e3, $timeout_ms * 1e3);
            $n  = min(64e3, $timeout_ms * 1e3);
            if ($m == $n) {
                $m = ($n >> 1) + 1;
            }

            $timeout_ms = (float) $timeout_ms / 1000;
            // If lock not obtained sleep for 0 - 64 milliseconds, to avoid collision and CPU load
            do {
                usleep($t = rand($m, $n));
                $l = flock($fp, $lock);
            } while (!$l && (microtime(true) - $st) < $timeout_ms);
        }
        return $l;
    }
public static function do_flock ( $ fp , $ lock , $ timeout_ms = 384 ) { $ l = flock ( $ fp , $ lock ) ; if ( ! $ l && ( $ lock & LOCK_UN ) != LOCK_UN ) { $ st = microtime ( true ) ; $ m = min ( 1e3 , $ timeout_ms * 1e3 ) ; $ n = min ( 64e3 , $ timeout_ms * 1e3 ) ; if ( $ m == $ n ) { $ m = ( $ n >> 1 ) + 1 ; } $ timeout_ms = ( float ) $ timeout_ms / 1000 ; // If lock not obtained sleep for 0 - 64 milliseconds, to avoid collision and CPU load do { usleep ( $ t = rand ( $ m , $ n ) ) ; $ l = flock ( $ fp , $ lock ) ; } while ( ! $ l && ( microtime ( true ) - $ st ) < $ timeout_ms ) ; } return $ l ; }
Lock with retries

@author Dumitru Uzun

@param  resource $fp         - Open file pointer
@param  int      $lock       - Lock type
@param  int      $timeout_ms - OPTIONAL Timeout to wait for unlock in miliseconds
@return true     on success, false on fail
Lock with retries