Skip to content

Instantly share code, notes, and snippets.

@yaniaular
Last active February 19, 2022 06:09
Show Gist options
  • Save yaniaular/981421ba3b3c8724316fa27d61633d5c to your computer and use it in GitHub Desktop.
Save yaniaular/981421ba3b3c8724316fa27d61633d5c to your computer and use it in GitHub Desktop.
How works redis.lock with python
# https://github.com/redis/redis-py/
# https://realpython.com/intro-to-python-threading/
import time
import threading
from redis import Redis
from redis.exceptions import LockError, TimeoutError, LockNotOwnedError
r = Redis(host='localhost', port=6379, db=0)
print("Starting...")
def multiple_locks(thread: str):
do_lock(f"{thread}-lock1")
do_lock(f"{thread}-lock2")
do_lock(f"{thread}-lock3")
do_lock(f"{thread}-lock4")
do_lock(f"{thread}-lock5")
def do_lock(key: str):
try:
# timeout-en: limit time to release the lock, i.e, if the code hasn't finished
# and the timeout is running out, then, the LockNotOwnedError exception occurs and
# the lock is interrupted and it can receives a new lock with the same key that just finished.
# If it's executing the code and the timeout is running out and it hasn't finished,
# the print("Codigo adicional") will be not executed, example sleep=5 y timeout=4 (sleep >= timeout)
# And the LockNotOwnedError exception will be executed.
# blocking_timeout-en: If come a lock with a key that it's already processing, then,
# it's going to wait 3 seconds to try acquire the lock. If 3 seconds are up and the key
# continue executing, then, the LockError exception will be displayed.
# timeout-es: tiempo que se da para liberar el lock, es decir, si el codigo no ha terminado
# y se cumple el timeout entonces ocurrirá la excepción LockNotOwnedError y se interrumpe
# el lock y se podrá recibir un nuevo lock con el mismo key que acaba de terminar.
# Si está ejecutándose el código y se cumple el timeout y no ha terminado, no se
# ejecutará el print("Codigo adicional"), ejemplo sleep=5 y timeout=4 (sleep >= timeout)
# Y se ejecutará la excepcion LockNotOwnedError
# blocking_timeout-es: Si viene un lock con un key que ya se esta procesando entonces va a
# esperar 3 segundos para intentar adquirir el lock. Si pasan los 3 segundos y el key
# sigue ejecutandose, entonces dará la excepción LockError.
with r.lock("lock-key", timeout=5, blocking_timeout=1) as lock:
print(f"Inicia el lock {key}")
time.sleep(6)
print(f"Terminó el lock {key}")
print("Codigo adicional")
except LockNotOwnedError:
print(f"the lock {key} wasn't released")
except LockError:
print(f"the lock {key} wasn't acquired")
thread1 = threading.Thread(target=multiple_locks, args=("thread1",))
thread2 = threading.Thread(target=multiple_locks, args=("thread2",))
thread1.start()
thread2.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment