File: locks.py

package info (click to toggle)
python-aiohttp 3.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 5,612 kB
  • sloc: python: 36,917; ansic: 15,734; makefile: 365; sh: 83
file content (45 lines) | stat: -rw-r--r-- 1,235 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import asyncio
import collections
from typing import Any, Optional


try:
    from typing import Deque
except ImportError:
    from typing_extensions import Deque  # noqa


class EventResultOrError:
    """
    This class wrappers the Event asyncio lock allowing either awake the
    locked Tasks without any error or raising an exception.

    thanks to @vorpalsmith for the simple design.
    """
    def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
        self._loop = loop
        self._exc = None  # type: Optional[BaseException]
        self._event = asyncio.Event(loop=loop)
        self._waiters = collections.deque()  # type: Deque[asyncio.Future[Any]]

    def set(self, exc: Optional[BaseException]=None) -> None:
        self._exc = exc
        self._event.set()

    async def wait(self) -> Any:
        waiter = self._loop.create_task(self._event.wait())
        self._waiters.append(waiter)
        try:
            val = await waiter
        finally:
            self._waiters.remove(waiter)

        if self._exc is not None:
            raise self._exc

        return val

    def cancel(self) -> None:
        """ Cancel all waiters """
        for waiter in self._waiters:
            waiter.cancel()