Monday, August 30, 2010

A simple distributed lock with memcached... in Python

Following Sylvain's advice I just wrote a memcache lock in Python:

class Lock():
def __init__(self, key):
self.key = "lock.%s" % key

def __enter__(self):
while True:
value = getClient().add(self.key, "1", 60000)
if value == True:
return
time.sleep(.1)

def __exit__(self, exc_type, exc_val, exc_tb):
getClient().delete(self.key)
return False


Using the lock is as simple as doing:

with Lock("critical1"):
doSomeExpensiveStuff()


The advantage over Sylvain's Java version is that the locking code is reusable, thanks to the use of a Python context manager.

2 comments:

Unknown said...

Is it a Memcached Mutex ? I don't get it =)

Tiffiny said...

Cool!