You are here

function lock_acquire in Memcache API and Integration 6

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

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

Parameters

$name: The name of the lock.

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

Return value

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

4 calls to lock_acquire()
cache_get in ./memcache.inc
Return data from the persistent cache.
LockFunctionalTest::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.

File

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

Code

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

  // 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]);
}