Skip to content

Commit

Permalink
Add thread safety to lock
Browse files Browse the repository at this point in the history
  • Loading branch information
taylor-cedar committed Sep 18, 2018
1 parent 60ddfe0 commit 4a24a1f
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions fakeredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import types
import re
import functools
import threading
from itertools import count, islice
from uuid import uuid4

Expand Down Expand Up @@ -311,6 +312,9 @@ def _compile_pattern(pattern):
return re.compile(regex, re.S)


threading_lock = threading.Lock()


class _Lock(object):
def __init__(self, redis, name, timeout):
self.redis = redis
Expand All @@ -327,7 +331,8 @@ def __exit__(self, exc_type, exc_value, traceback):

def acquire(self, blocking=True, blocking_timeout=None):
token = str(uuid4())
acquired = bool(self.redis.set(self.name, token, nx=True, ex=self.timeout))
with threading_lock:
acquired = bool(self.redis.set(self.name, token, nx=True, ex=self.timeout))
if not acquired and blocking:
raise ValueError('fakeredis can\'t do blocking locks')

Expand All @@ -340,11 +345,12 @@ def release(self):
if self.id is None:
raise LockError("Cannot release an unlocked lock")

if _decode(self.redis.get(self.name)) != self.id:
raise LockError("Cannot release a lock that's no longer owned")
with threading_lock:
if _decode(self.redis.get(self.name)) != self.id:
raise LockError("Cannot release a lock that's no longer owned")

self.redis.delete(self.name)
self.id = None
self.redis.delete(self.name)
self.id = None


def _check_conn(func):
Expand Down

0 comments on commit 4a24a1f

Please sign in to comment.