note 82277 modified in function.memcache-add by danbrown

From: Date: Sat, 19 Jun 2010 03:53:33 +0000
Subject: note 82277 modified in function.memcache-add by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-170268@lists.php.net to get a copy of this message
memcache has no locking mechanism, but you could implement it manually. basic locking through the add method: <?php // locks time out after 5 seconds Define( 'LOCK_TIMEOUT', 5 ); $lock = $memcache->add( 'lock:' . $key, 1, false, LOCK_TIMEOUT ); if ( $lock ) { // no lock on this key, so do what you want $value = $memcache->get( $key ); $memcache->set( $key, $value+1 ); // release lock $memcache->delete( 'lock:' . $key ); } else { // variable is currently locked, so do something else } ?> furthermore, you could implement a loop which checks if there is a lock, and if there is, wait some time and try again, until the lock is free. remember: locking will heavily increase your memcache hits and obviously is not what memcache is made for. altough it's not possible for a lock to be forgotten (there's a timeout after all) there is the possibility to get locked out for a very long time. an alternative may be to implement locking through apc_add (or shared memory), but i've never tried it. if you absolutley have to implement locks, memcached is probably the wrong solution anyway. --was-- memcache has no locking mechanism, but you could implement it manually. basic locking through the add method: <?php // locks time out after 5 seconds Define( 'LOCK_TIMEOUT', 5 ); $lock = $memcache->add( 'lock:' . $key, 1, false, LOCK_TIMEOUT ); if ( $lock ) { // no lock on this key, so do what you want $value = $memcache->get( $key ); $memcache->set( $key, $value+1 ); // release lock $memcache->delete( 'lock:' . $key ); } else { // variable is currently locked, so do something else } ?> furthermore, you could implement a loop which checks if there is a lock, and if there is, wait some time and try again, until the lock is free. remember: locking will heavily increase your memcache hits and obviously is not what memcache is made for. altough it's not possible for a lock to be forgotten (there's a timeout after all) there is the possibility to get locked out for a very long time. an alternative may be to implement locking through apc_add (or shared memory), but i've never tried it. if you absolutley have to implement locks, memcached is probably the wrong solution anyway. http://php.net/manual/en/function.memcache-add.php

« previous php.notes (#170268) next »