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;
    }