Skip to content

Instantly share code, notes, and snippets.

@shofetim
Created April 17, 2013 23:14
Show Gist options
  • Select an option

  • Save shofetim/5408539 to your computer and use it in GitHub Desktop.

Select an option

Save shofetim/5408539 to your computer and use it in GitHub Desktop.
@contextmanager
def exploding_redis_mutex(key, timeout=10):
r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)
mutex_key = ('mutex', key)
while not r.setnx(mutex_key, datetime.now()):
val = datetime.strptime(r.get(mutex_key), '%Y-%m-%d %H:%M:%S.%f')
if (datetime.now() - val).seconds > timeout:
r.delete(mutex_key)
else:
raise RedisMutexLockedError("'%s' is already locked in the mutex" % (key,))
try:
yield True
finally:
r.delete(mutex_key)
del(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment