public function lock($key, $ownerid, $block = false) {
        // Get the name of the lock file we want to use.
        $lockfile = $this->get_lock_file($key);

        // Attempt to create a handle to the lock file.
        // Mode xb is the secret to this whole function.
        //   x = Creates the file and opens it for writing. If the file already exists fopen returns false and a warning is thrown.
        //   b = Forces binary mode.
        $result = @fopen($lockfile, 'xb');

        // Check if we could create the file or not.
        if ($result === false) {
            // Lock exists already.
            if ($this->maxlife !== null && !array_key_exists($key, $this->locks)) {
                $mtime = filemtime($lockfile);
                if ($mtime < time() - $this->maxlife) {
                    $this->unlock($key, true);
                    $result = $this->lock($key, false);
                    if ($result) {
                        return true;
                    }
                }
            }
            if ($block) {
                // OK we are blocking. We had better sleep and then retry to lock.
                $iterations = 0;
                $maxiterations = $this->blockattempts;
                while (($result = $this->lock($key, false)) === false) {
                    // Usleep causes the application to cleep to x microseconds.
                    // Before anyone asks there are 1'000'000 microseconds to a second.
                    usleep(rand(1000, 50000)); // Sleep between 1 and 50 milliseconds.
                    $iterations++;
                    if ($iterations > $maxiterations) {
                        // BOOM! We've exceeded the maximum number of iterations we want to block for.
                        throw new cache_exception('ex_unabletolock');
                    }
                }
            }

            return false;
        } else {
            // We have the lock.
            fclose($result);
            $this->locks[$key] = $lockfile;
            return true;
        }
    }