You are here

function lock_acquire in Memcache API and Integration 7

Same name and namespace in other branches
  1. 6 memcache-lock-code.inc \lock_acquire()

Acquire (or renew) a lock, but do not block if it fails.

Parameters

string $name: The name of the lock.

int $timeout: A number of seconds (int) before the lock expires (minimum of 1).

Return value

bool TRUE if the lock was acquired, FALSE if it failed.

4 calls to lock_acquire()
MemCacheDrupal::valid in ./memcache.inc
Checks if a retrieved cache item is valid.
MemcacheLockFunctionalTest::testLockAcquire in tests/memcache-lock.test
Confirm that we can acquire and release locks in two parallel requests.
memcache_test_lock_acquire in tests/memcache_test.module
Try to acquire a named lock and report the outcome.
memcache_test_lock_exit in tests/memcache_test.module
Try to acquire a specific lock, and then exit.
1 string reference to 'lock_acquire'
MemCacheDrupal::lockInit in ./memcache.inc
Helper function to load locking framework if not already loaded.

File

./memcache-lock-code.inc, line 32
A memcache based implementation of a locking mechanism. See includes/lock.inc for documenation

Code

function lock_acquire($name, $timeout = 30) {
  global $locks;

  // Special case variable_init, as on memcache errors we can get stuck in an
  // infinite loop.
  static $variable_init = 0;
  if ($name == 'variable_init') {
    if ($variable_init > 25) {
      register_shutdown_function('watchdog', 'memcache', 'Broke out of loop trying to grab lock for variable_init.');
      return TRUE;
    }
    $variable_init++;
  }

  // Ensure that the timeout is at least 1 sec. This is a limitation
  // imposed by memcached.
  $timeout = (int) max($timeout, 1);
  if (dmemcache_add($name, _lock_id(), $timeout, 'semaphore')) {
    $locks[$name] = _lock_id();
  }
  elseif (($result = dmemcache_get($name, 'semaphore')) && isset($locks[$name]) && $locks[$name] == $result) {

    // Only renew the lock if we already set it and it has not expired.
    dmemcache_set($name, _lock_id(), $timeout, 'semaphore');
  }
  else {

    // Failed to acquire the lock.  Unset the key from the $locks array even if
    // not set, PHP 5+ allows this without error or warning.
    unset($locks[$name]);
  }
  return isset($locks[$name]);
}