Feature request: lock a key

Jamie McCarthy jamie at mccarthy.vg
Fri Sep 10 09:38:39 PDT 2004

You could implement locking using any other mechanism that
supports it of course:  flock() on a local filesystem,
LOCK TABLE on a database table or something.  Or you can do this
using memcached's incr and decr, which atomically increment a
value you can use as a semaphore:

sub get_lock {
    my $val;
    while (1) {
        $val = $cache->incr("mykey");
        return 1 if !defined($val); # means we're the first lock ever
        return 1 if $val == 1; # means we got the lock
        # $val must be > 1, so we didn't get the lock (yet)
        $cache->decr("mykey"); # give up our claim
        # might be nice here to bomb out w/error after n retries
        Time::HiRes::sleep(rand()); # wait random time before retrying

sub release_lock {

To be robust about it, you'd probably want signal handlers that
clean up any locks you're holding, else ^C'ing your program at the
wrong time could keep every other program from using that resource.
Maybe you could write an object that grabs the lock when it's
created and gives it up in its DESTROY method, so you'd be less
likely to goof up and call the wrong function once too often.

Of course, if you wanted robustness, you wouldn't be using a
storage mechanism that is specifically designed to handle some of
its servers going down every so often and throwing some or all of
its data away and starting over.  I hope you're using this for
quickie projects and not my bank account :)
  Jamie McCarthy
  jamie at mccarthy.vg

More information about the memcached mailing list