Skip to content

Commit ed76c31

Browse files
committed
Add simple lock thing
1 parent aa3418b commit ed76c31

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

mautrix/util/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
__all__ = ["formatter", "color_log", "config", "signed_token", "simple_template", "manhole",
2-
"markdown"]
2+
"markdown", "simple_lock"]

mautrix/util/simple_lock.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Copyright (c) 2020 Tulir Asokan
2+
#
3+
# This Source Code Form is subject to the terms of the Mozilla Public
4+
# License, v. 2.0. If a copy of the MPL was not distributed with this
5+
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
6+
from typing import Optional
7+
import logging
8+
import asyncio
9+
10+
11+
class SimpleLock:
12+
_loop: asyncio.AbstractEventLoop
13+
_future: Optional[asyncio.Future]
14+
log: Optional[logging.Logger]
15+
message: Optional[str]
16+
17+
def __init__(self, message: Optional[str] = None, log: Optional[logging.Logger] = None,
18+
loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
19+
self._future = None
20+
self._loop = loop or asyncio.get_event_loop()
21+
self.log = log
22+
self.message = message
23+
24+
def __enter__(self) -> None:
25+
if self._future is None or self._future.done():
26+
self._future = self._loop.create_future()
27+
28+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
29+
if self._future is not None:
30+
self._future.set_result(None)
31+
self._future = None
32+
33+
@property
34+
def locked(self) -> bool:
35+
return self._future is not None and not self._future.done()
36+
37+
async def wait(self, task: Optional[str] = None) -> None:
38+
if self._future is not None:
39+
if self.log and self.message:
40+
self.log.debug(self.message, task)
41+
await self._future

0 commit comments

Comments
 (0)