Skip to content

Commit

Permalink
Replaced RLock reimplementation with Gevent RLock
Browse files Browse the repository at this point in the history
  • Loading branch information
Joel Collins committed Apr 14, 2020
1 parent 2d2e94a commit e9f9291
Showing 1 changed file with 2 additions and 68 deletions.
70 changes: 2 additions & 68 deletions labthings/core/lock.py
Original file line number Diff line number Diff line change
@@ -1,79 +1,13 @@
from gevent.hub import getcurrent
from gevent._semaphore import Semaphore
from gevent.lock import RLock as _RLock

from .exceptions import LockError


class RLock(object):
"""
A mutex that can be acquired more than once by the same greenlet.
A mutex can only be locked by one greenlet at a time. A single greenlet
can `acquire` the mutex as many times as desired, though. Each call to
`acquire` must be paired with a matching call to `release`.
It is an error for a greenlet that has not acquired the mutex
to release it.
Instances are context managers.
"""

__slots__ = ("_block", "_owner", "_count", "__weakref__")

def __init__(self):
self._block = Semaphore(1)
self._owner = None
self._count = 0

def __repr__(self):
return "<%s at 0x%x _block=%s _count=%r _owner=%r)>" % (
self.__class__.__name__,
id(self),
self._block,
self._count,
self._owner,
)

class RLock(_RLock):
def locked(self):
return self._block.locked()

def acquire(self, blocking=True, timeout=None):
"""
Acquire the mutex, blocking if *blocking* is true, for up to
*timeout* seconds.
.. versionchanged:: 1.5a4
Added the *timeout* parameter.
:return: A boolean indicating whether the mutex was acquired.
"""
me = getcurrent()
if self._owner is me:
self._count = self._count + 1
return 1
rc = self._block.acquire(blocking, timeout)
if rc:
self._owner = me
self._count = 1
return rc

def __enter__(self):
return self.acquire()

def release(self):
"""
Release the mutex.
Only the greenlet that originally acquired the mutex can
release it.
"""
if self._owner is not getcurrent():
raise RuntimeError("cannot release un-acquired lock")
self._count = count = self._count - 1
if not count:
self._owner = None
self._block.release()

def __exit__(self, typ, value, tb):
self.release()

def _is_owned(self):
return self._owner is getcurrent()


class StrictLock:
"""
Expand Down

0 comments on commit e9f9291

Please sign in to comment.