Back to FileStorage class

Method lock

public mixed
lock
(mixed $id, mixed $group, mixed $locktime)
Lock cached item
Parameters
  • string $id The cache data ID
  • string $group The cache data group
  • int $locktime Cached item max lock time
Returns
  • mixed Boolean false if locking failed or an object containing properties lock and locklooped
Since
  • 1.7.0
Class: FileStorage
Project: Joomla

Method lock - Source code

/**
 * Lock cached item
 *
 * @param   string   $id        The cache data ID
 * @param   string   $group     The cache data group
 * @param   integer  $locktime  Cached item max lock time
 *
 * @return  mixed  Boolean false if locking failed or an object containing properties lock and locklooped
 *
 * @since   1.7.0
 */
public function lock($id, $group, $locktime)
{
    $returning = new \stdClass();
    $returning->locklooped = false;
    $looptime = $locktime * 10;
    $path = $this->_getFilePath($id, $group);
    $_fileopen = @fopen($path, 'c+b');
    if (!$_fileopen) {
        $returning->locked = false;
        return $returning;
    }
    $data_lock = (bool) @flock($_fileopen, LOCK_EX | LOCK_NB);
    if ($data_lock === false) {
        $lock_counter = 0;
        // Loop until you find that the lock has been released.
        // That implies that data get from other thread has finished
        while ($data_lock === false) {
            if ($lock_counter > $looptime) {
                break;
            }
            usleep(100);
            $data_lock = (bool) @flock($_fileopen, LOCK_EX | LOCK_NB);
            $lock_counter++;
        }
        $returning->locklooped = true;
    }
    if ($data_lock === true) {
        // Remember resource, flock release lock if you unset/close resource
        $this->_locked_files[$path] = $_fileopen;
    }
    $returning->locked = $data_lock;
    return $returning;
}