Last active
December 28, 2017 20:40
-
-
Save NiklasRosenstein/e8b494a4d79519d74751f2c4cc79923d to your computer and use it in GitHub Desktop.
This is just hacked together real quick, not 100% production proven.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
class RLock(asyncio.Lock): | |
""" | |
A reentrant lock for Python coroutines. | |
""" | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self._task = None | |
self._depth = 0 | |
@asyncio.coroutine | |
def acquire(self): | |
if self._task is None or self._task != asyncio.Task.current_task(): | |
yield from super().acquire() | |
self._task = asyncio.Task.current_task() | |
assert self._depth == 0 | |
self._depth += 1 | |
def release(self): | |
if self._depth > 0: | |
self._depth -= 1 | |
if self._depth == 0: | |
super().release() | |
self._task = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not sure why, but we need to use the
@coroutine
decorator forRLock.acquire()
instead of theasync
keyword, as otherwise we'll get this error when usingwith await lock: