|
1 | 1 | from gevent.hub import getcurrent |
2 | | -from gevent._semaphore import Semaphore |
| 2 | +from gevent.lock import RLock as _RLock |
3 | 3 |
|
4 | 4 | from .exceptions import LockError |
5 | 5 |
|
6 | 6 |
|
7 | | -class RLock(object): |
8 | | - """ |
9 | | - A mutex that can be acquired more than once by the same greenlet. |
10 | | - A mutex can only be locked by one greenlet at a time. A single greenlet |
11 | | - can `acquire` the mutex as many times as desired, though. Each call to |
12 | | - `acquire` must be paired with a matching call to `release`. |
13 | | - It is an error for a greenlet that has not acquired the mutex |
14 | | - to release it. |
15 | | - Instances are context managers. |
16 | | - """ |
17 | | - |
18 | | - __slots__ = ("_block", "_owner", "_count", "__weakref__") |
19 | | - |
20 | | - def __init__(self): |
21 | | - self._block = Semaphore(1) |
22 | | - self._owner = None |
23 | | - self._count = 0 |
24 | | - |
25 | | - def __repr__(self): |
26 | | - return "<%s at 0x%x _block=%s _count=%r _owner=%r)>" % ( |
27 | | - self.__class__.__name__, |
28 | | - id(self), |
29 | | - self._block, |
30 | | - self._count, |
31 | | - self._owner, |
32 | | - ) |
33 | | - |
| 7 | +class RLock(_RLock): |
34 | 8 | def locked(self): |
35 | 9 | return self._block.locked() |
36 | 10 |
|
37 | | - def acquire(self, blocking=True, timeout=None): |
38 | | - """ |
39 | | - Acquire the mutex, blocking if *blocking* is true, for up to |
40 | | - *timeout* seconds. |
41 | | - .. versionchanged:: 1.5a4 |
42 | | - Added the *timeout* parameter. |
43 | | - :return: A boolean indicating whether the mutex was acquired. |
44 | | - """ |
45 | | - me = getcurrent() |
46 | | - if self._owner is me: |
47 | | - self._count = self._count + 1 |
48 | | - return 1 |
49 | | - rc = self._block.acquire(blocking, timeout) |
50 | | - if rc: |
51 | | - self._owner = me |
52 | | - self._count = 1 |
53 | | - return rc |
54 | | - |
55 | | - def __enter__(self): |
56 | | - return self.acquire() |
57 | | - |
58 | | - def release(self): |
59 | | - """ |
60 | | - Release the mutex. |
61 | | - Only the greenlet that originally acquired the mutex can |
62 | | - release it. |
63 | | - """ |
64 | | - if self._owner is not getcurrent(): |
65 | | - raise RuntimeError("cannot release un-acquired lock") |
66 | | - self._count = count = self._count - 1 |
67 | | - if not count: |
68 | | - self._owner = None |
69 | | - self._block.release() |
70 | | - |
71 | | - def __exit__(self, typ, value, tb): |
72 | | - self.release() |
73 | | - |
74 | | - def _is_owned(self): |
75 | | - return self._owner is getcurrent() |
76 | | - |
77 | 11 |
|
78 | 12 | class StrictLock: |
79 | 13 | """ |
|
0 commit comments