Repository navigation
Expand file tree
/
Copy pathsimple_sync.py
More file actions
148 lines (114 loc) · 4.76 KB
/
Copy pathsimple_sync.py
File metadata and controls
148 lines (114 loc) · 4.76 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# Copyright 2020-present Michael Hall
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
__lazy_modules__: list[str] = ["asyncio"]
import asyncio
import concurrent.futures as cf
import threading
from collections import deque
from . import _typings as t
# This is one of the few things that should unreservedly be reimplemented
# natively if that's something I decide to do.
# Atomic ops allow the removal of the internal locking.
# We can also do a little bit better prior to making it native by only locking
# if we observe multiple threads. The gain for this is minor, but not insignificant.
# This particular lock implementation optimizes for the uncontested lock case.
# This is the most important optimization for well-designed parallel code
# with fine-grained lock use. It's also barging, which is known to be better
# than FIFO in the case of highly contested locks.
class AsyncLock:
"""An async lock that doesn't bind to an event loop."""
def __init_subclass__(cls) -> t.Never:
msg = "Don't subclass this"
raise RuntimeError(msg)
__final__ = True
def __init__(self) -> None:
self._waiters: deque[cf.Future[None]] = deque()
self._lockv: bool = False
self._internal_lock: threading.RLock = threading.RLock()
async def __aenter__(self) -> None:
with self._internal_lock:
if not self._lockv:
self._lockv = True
return
fut: cf.Future[None] = cf.Future()
self._waiters.append(fut)
try:
await asyncio.wrap_future(fut)
except asyncio.CancelledError:
with self._internal_lock:
if not self._lockv:
self._maybe_wake()
raise
def _maybe_wake(self) -> None:
with self._internal_lock:
while (not self._lockv) and self._waiters:
next_waiter = self._waiters.popleft()
if not (next_waiter.done() or next_waiter.cancelled()):
self._lockv = True
next_waiter.set_result(None)
while self._waiters:
next_waiter = self._waiters.popleft()
if not (next_waiter.done() or next_waiter.cancelled()):
self._waiters.appendleft(next_waiter)
break
async def __aexit__(self, *dont_care: object) -> t.Literal[False]:
with self._internal_lock:
self._lockv = False
self._maybe_wake()
return False
class AsyncSemaphore:
"""An async semaphore that doesn't bind to an event loop."""
def __init_subclass__(cls) -> t.Never:
msg = "Don't subclass this"
raise RuntimeError(msg)
__final__ = True
def __init__(self, value: int = 1) -> None:
if value < 1:
msg = "Semaphore must have an initial value of at least 1"
raise ValueError(msg)
self._waiters: deque[cf.Future[None]] = deque()
self._value: int = value
self._internal_lock: threading.RLock = threading.RLock()
async def __aenter__(self) -> None:
with self._internal_lock:
if self._value > 0:
self._value -= 1
return
fut: cf.Future[None] = cf.Future()
self._waiters.append(fut)
try:
await asyncio.wrap_future(fut)
except asyncio.CancelledError:
with self._internal_lock:
if self._value > 0:
self._maybe_wake()
raise
def _maybe_wake(self) -> None:
with self._internal_lock:
while (self._value > 0) and self._waiters:
next_waiter = self._waiters.popleft()
if not (next_waiter.done() or next_waiter.cancelled()):
self._value -= 1
next_waiter.set_result(None)
while self._waiters:
next_waiter = self._waiters.popleft()
if not (next_waiter.done() or next_waiter.cancelled()):
self._waiters.appendleft(next_waiter)
break
async def __aexit__(self, *dont_care: object) -> t.Literal[False]:
with self._internal_lock:
self._value += 1
self._maybe_wake()
return False