Skip to content

Instantly share code, notes, and snippets.

@zhyq0826 zhyq0826/
Last active Aug 18, 2016

What would you like to do?
python code for redis lock
import time
import redis
import logging
logger = logging.getLogger('service.redis_lock')
CONN = redis.Redis(host='localhost')
def acquire_lock(lockname, identifier, wait_time=20, timeout=15):
end = time.time() + wait_time
while end > time.time():
if CONN.setnx(lockname, identifier):
CONN.expire(lockname, timeout) # set expire time
return identifier
time.sleep(0.001) #wait until the lock expired or release by some thread
return False
def release_lock(lockname, identifier):
pipe = CONN.pipeline(True)
#watch lock once lock has been changed, break this transaction
#check if lock has been changed
if pipe.get(lockname) == identifier:
return True
pipe.unwatch() #execu when identifier not equal
except redis.exceptions.WatchError as e:
return False
except Exception as e:
return False
return False
if __name__ == '__main__':
print release_lock('h', 'a')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.