@contextmanager
def Mutex(client, name, expire):
 lock_id = uuid()
 i_won = client.setnx(name, lock_id)
 try:
  if i_won:
   client.expire(name, expire)
   (yield)
  else:
   if (not client.ttl(name)):
    client.expire(name, expire)
   raise MutexHeld()
 finally:
  if i_won:
   try:
    with client.pipeline(True) as pipe:
     pipe.watch(name)
     if (pipe.get(name) == lock_id):
      pipe.multi()
      pipe.delete(name)
      pipe.execute()
     pipe.unwatch()
   except redis.WatchError:
    pass

@ contextmanager def Mutex ( client , name , expire ) : lock_id = uuid ( ) i_won = client . setnx ( name , lock_id ) try : if i_won : client . expire ( name , expire ) ( yield ) else : if ( not client . ttl ( name ) ) : client . expire ( name , expire ) raise MutexHeld ( ) finally : if i_won : try : with client . pipeline ( True ) as pipe : pipe . watch ( name ) if ( pipe . get ( name ) == lock_id ) : pipe . multi ( ) pipe . delete ( name ) pipe . execute ( ) pipe . unwatch ( ) except redis . WatchError : pass
the redis lock implementation .