| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import math |
| 4 |
from typing import TYPE_CHECKING, Literal, Protocol |
| 5 |
|
| 6 |
import attrs |
| 7 |
|
| 8 |
import trio |
| 9 |
|
| 10 |
from . import _core |
| 11 |
from ._core import ( |
| 12 |
Abort, |
| 13 |
ParkingLot, |
| 14 |
RaiseCancelT, |
| 15 |
add_parking_lot_breaker, |
| 16 |
enable_ki_protection, |
| 17 |
remove_parking_lot_breaker, |
| 18 |
) |
| 19 |
from ._util import final |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from types import TracebackType |
| 23 |
|
| 24 |
from ._core import Task |
| 25 |
from ._core._parking_lot import ParkingLotStatistics |
| 26 |
|
| 27 |
|
| 28 |
@attrs.frozen |
| 29 |
class EventStatistics: |
| 30 |
"""An object containing debugging information. |
| 31 |
|
| 32 |
Currently the following fields are defined: |
| 33 |
|
| 34 |
* ``tasks_waiting``: The number of tasks blocked on this event's |
| 35 |
:meth:`trio.Event.wait` method. |
| 36 |
|
| 37 |
""" |
| 38 |
|
| 39 |
tasks_waiting: int |
| 40 |
|
| 41 |
|
| 42 |
@final |
| 43 |
@attrs.define(repr=False, eq=False) |
| 44 |
class Event: |
| 45 |
"""A waitable boolean value useful for inter-task synchronization, |
| 46 |
inspired by :class:`threading.Event`. |
| 47 |
|
| 48 |
An event object has an internal boolean flag, representing whether |
| 49 |
the event has happened yet. The flag is initially False, and the |
| 50 |
:meth:`wait` method waits until the flag is True. If the flag is |
| 51 |
already True, then :meth:`wait` returns immediately. (If the event has |
| 52 |
already happened, there's nothing to wait for.) The :meth:`set` method |
| 53 |
sets the flag to True, and wakes up any waiters. |
| 54 |
|
| 55 |
This behavior is useful because it helps avoid race conditions and |
| 56 |
lost wakeups: it doesn't matter whether :meth:`set` gets called just |
| 57 |
before or after :meth:`wait`. If you want a lower-level wakeup |
| 58 |
primitive that doesn't have this protection, consider :class:`Condition` |
| 59 |
or :class:`trio.lowlevel.ParkingLot`. |
| 60 |
|
| 61 |
.. note:: Unlike `threading.Event`, `trio.Event` has no |
| 62 |
`~threading.Event.clear` method. In Trio, once an `Event` has happened, |
| 63 |
it cannot un-happen. If you need to represent a series of events, |
| 64 |
consider creating a new `Event` object for each one (they're cheap!), |
| 65 |
or other synchronization methods like :ref:`channels <channels>` or |
| 66 |
`trio.lowlevel.ParkingLot`. |
| 67 |
|
| 68 |
""" |
| 69 |
|
| 70 |
_tasks: set[Task] = attrs.field(factory=set, init=False) |
| 71 |
_flag: bool = attrs.field(default=False, init=False) |
| 72 |
|
| 73 |
def is_set(self) -> bool: |
| 74 |
"""Return the current value of the internal flag.""" |
| 75 |
return self._flag |
| 76 |
|
| 77 |
@enable_ki_protection |
| 78 |
def set(self) -> None: |
| 79 |
"""Set the internal flag value to True, and wake any waiting tasks.""" |
| 80 |
if not self._flag: |
| 81 |
self._flag = True |
| 82 |
for task in self._tasks: |
| 83 |
_core.reschedule(task) |
| 84 |
self._tasks.clear() |
| 85 |
|
| 86 |
async def wait(self) -> None: |
| 87 |
"""Block until the internal flag value becomes True. |
| 88 |
|
| 89 |
If it's already True, then this method returns immediately. |
| 90 |
|
| 91 |
""" |
| 92 |
if self._flag: |
| 93 |
await trio.lowlevel.checkpoint() |
| 94 |
else: |
| 95 |
task = _core.current_task() |
| 96 |
self._tasks.add(task) |
| 97 |
|
| 98 |
def abort_fn(_: RaiseCancelT) -> Abort: |
| 99 |
self._tasks.remove(task) |
| 100 |
return _core.Abort.SUCCEEDED |
| 101 |
|
| 102 |
await _core.wait_task_rescheduled(abort_fn) |
| 103 |
|
| 104 |
def statistics(self) -> EventStatistics: |
| 105 |
"""Return an object containing debugging information. |
| 106 |
|
| 107 |
Currently the following fields are defined: |
| 108 |
|
| 109 |
* ``tasks_waiting``: The number of tasks blocked on this event's |
| 110 |
:meth:`wait` method. |
| 111 |
|
| 112 |
""" |
| 113 |
return EventStatistics(tasks_waiting=len(self._tasks)) |
| 114 |
|
| 115 |
def __bool__(self) -> Literal[True]: |
| 116 |
"""Raise error.""" |
| 117 |
raise NotImplementedError( |
| 118 |
"Trio events cannot be treated as bools; consider using `event.is_set()` instead." |
| 119 |
) |
| 120 |
|
| 121 |
|
| 122 |
class _HasAcquireRelease(Protocol): |
| 123 |
"""Only classes with acquire() and release() can use the mixin's implementations.""" |
| 124 |
|
| 125 |
async def acquire(self) -> object: ... |
| 126 |
|
| 127 |
def release(self) -> object: ... |
| 128 |
|
| 129 |
|
| 130 |
class AsyncContextManagerMixin: |
| 131 |
@enable_ki_protection |
| 132 |
async def __aenter__(self: _HasAcquireRelease) -> None: |
| 133 |
await self.acquire() |
| 134 |
|
| 135 |
@enable_ki_protection |
| 136 |
async def __aexit__( |
| 137 |
self: _HasAcquireRelease, |
| 138 |
exc_type: type[BaseException] | None, |
| 139 |
exc_value: BaseException | None, |
| 140 |
traceback: TracebackType | None, |
| 141 |
) -> None: |
| 142 |
self.release() |
| 143 |
|
| 144 |
|
| 145 |
@attrs.frozen |
| 146 |
class CapacityLimiterStatistics: |
| 147 |
"""An object containing debugging information. |
| 148 |
|
| 149 |
Currently the following fields are defined: |
| 150 |
|
| 151 |
* ``borrowed_tokens``: The number of tokens currently borrowed from |
| 152 |
the sack. |
| 153 |
* ``total_tokens``: The total number of tokens in the sack. Usually |
| 154 |
this will be larger than ``borrowed_tokens``, but it's possibly for |
| 155 |
it to be smaller if :attr:`trio.CapacityLimiter.total_tokens` was recently decreased. |
| 156 |
* ``borrowers``: A list of all tasks or other entities that currently |
| 157 |
hold a token. |
| 158 |
* ``tasks_waiting``: The number of tasks blocked on this |
| 159 |
:class:`CapacityLimiter`\'s :meth:`trio.CapacityLimiter.acquire` or |
| 160 |
:meth:`trio.CapacityLimiter.acquire_on_behalf_of` methods. |
| 161 |
|
| 162 |
""" |
| 163 |
|
| 164 |
borrowed_tokens: int |
| 165 |
total_tokens: int | float |
| 166 |
borrowers: list[Task | object] |
| 167 |
tasks_waiting: int |
| 168 |
|
| 169 |
|
| 170 |
# Can be a generic type with a default of Task if/when PEP 696 is released |
| 171 |
# and implemented in type checkers. Making it fully generic would currently |
| 172 |
# introduce a lot of unnecessary hassle. |
| 173 |
@final |
| 174 |
class CapacityLimiter(AsyncContextManagerMixin): |
| 175 |
"""An object for controlling access to a resource with limited capacity. |
| 176 |
|
| 177 |
Sometimes you need to put a limit on how many tasks can do something at |
| 178 |
the same time. For example, you might want to use some threads to run |
| 179 |
multiple blocking I/O operations in parallel... but if you use too many |
| 180 |
threads at once, then your system can become overloaded and it'll actually |
| 181 |
make things slower. One popular solution is to impose a policy like "run |
| 182 |
up to 40 threads at the same time, but no more". But how do you implement |
| 183 |
a policy like this? |
| 184 |
|
| 185 |
That's what :class:`CapacityLimiter` is for. You can think of a |
| 186 |
:class:`CapacityLimiter` object as a sack that starts out holding some fixed |
| 187 |
number of tokens:: |
| 188 |
|
| 189 |
limit = trio.CapacityLimiter(40) |
| 190 |
|
| 191 |
Then tasks can come along and borrow a token out of the sack:: |
| 192 |
|
| 193 |
# Borrow a token: |
| 194 |
async with limit: |
| 195 |
# We are holding a token! |
| 196 |
await perform_expensive_operation() |
| 197 |
# Exiting the 'async with' block puts the token back into the sack |
| 198 |
|
| 199 |
And crucially, if you try to borrow a token but the sack is empty, then |
| 200 |
you have to wait for another task to finish what it's doing and put its |
| 201 |
token back first before you can take it and continue. |
| 202 |
|
| 203 |
Another way to think of it: a :class:`CapacityLimiter` is like a sofa with a |
| 204 |
fixed number of seats, and if they're all taken then you have to wait for |
| 205 |
someone to get up before you can sit down. |
| 206 |
|
| 207 |
By default, :func:`trio.to_thread.run_sync` uses a |
| 208 |
:class:`CapacityLimiter` to limit the number of threads running at once; |
| 209 |
see `trio.to_thread.current_default_thread_limiter` for details. |
| 210 |
|
| 211 |
If you're familiar with semaphores, then you can think of this as a |
| 212 |
restricted semaphore that's specialized for one common use case, with |
| 213 |
additional error checking. For a more traditional semaphore, see |
| 214 |
:class:`Semaphore`. |
| 215 |
|
| 216 |
.. note:: |
| 217 |
|
| 218 |
Don't confuse this with the `"leaky bucket" |
| 219 |
<https://en.wikipedia.org/wiki/Leaky_bucket>`__ or `"token bucket" |
| 220 |
<https://en.wikipedia.org/wiki/Token_bucket>`__ algorithms used to |
| 221 |
limit bandwidth usage on networks. The basic idea of using tokens to |
| 222 |
track a resource limit is similar, but this is a very simple sack where |
| 223 |
tokens aren't automatically created or destroyed over time; they're |
| 224 |
just borrowed and then put back. |
| 225 |
|
| 226 |
""" |
| 227 |
|
| 228 |
# total_tokens would ideally be int|Literal[math.inf] - but that's not valid typing |
| 229 |
def __init__(self, total_tokens: int | float) -> None: # noqa: PYI041 |
| 230 |
self._lot = ParkingLot() |
| 231 |
self._borrowers: set[Task | object] = set() |
| 232 |
# Maps tasks attempting to acquire -> borrower, to handle on-behalf-of |
| 233 |
self._pending_borrowers: dict[Task, Task | object] = {} |
| 234 |
# invoke the property setter for validation |
| 235 |
self.total_tokens: int | float = total_tokens |
| 236 |
assert self._total_tokens == total_tokens |
| 237 |
|
| 238 |
def __repr__(self) -> str: |
| 239 |
return f"<trio.CapacityLimiter at {id(self):#x}, {len(self._borrowers)}/{self._total_tokens} with {len(self._lot)} waiting>" |
| 240 |
|
| 241 |
@property |
| 242 |
def total_tokens(self) -> int | float: |
| 243 |
"""The total capacity available. |
| 244 |
|
| 245 |
You can change :attr:`total_tokens` by assigning to this attribute. If |
| 246 |
you make it larger, then the appropriate number of waiting tasks will |
| 247 |
be woken immediately to take the new tokens. If you decrease |
| 248 |
total_tokens below the number of tasks that are currently using the |
| 249 |
resource, then all current tasks will be allowed to finish as normal, |
| 250 |
but no new tasks will be allowed in until the total number of tasks |
| 251 |
drops below the new total_tokens. |
| 252 |
|
| 253 |
""" |
| 254 |
return self._total_tokens |
| 255 |
|
| 256 |
@total_tokens.setter |
| 257 |
def total_tokens(self, new_total_tokens: int | float) -> None: # noqa: PYI041 |
| 258 |
if not isinstance(new_total_tokens, int) and new_total_tokens != math.inf: |
| 259 |
raise TypeError("total_tokens must be an int or math.inf") |
| 260 |
if new_total_tokens < 0: |
| 261 |
raise ValueError("total_tokens must be >= 0") |
| 262 |
self._total_tokens = new_total_tokens |
| 263 |
self._wake_waiters() |
| 264 |
|
| 265 |
def _wake_waiters(self) -> None: |
| 266 |
available = self._total_tokens - len(self._borrowers) |
| 267 |
for woken in self._lot.unpark(count=available): |
| 268 |
self._borrowers.add(self._pending_borrowers.pop(woken)) |
| 269 |
|
| 270 |
@property |
| 271 |
def borrowed_tokens(self) -> int: |
| 272 |
"""The amount of capacity that's currently in use.""" |
| 273 |
return len(self._borrowers) |
| 274 |
|
| 275 |
@property |
| 276 |
def available_tokens(self) -> int | float: |
| 277 |
"""The amount of capacity that's available to use.""" |
| 278 |
return self.total_tokens - self.borrowed_tokens |
| 279 |
|
| 280 |
@enable_ki_protection |
| 281 |
def acquire_nowait(self) -> None: |
| 282 |
"""Borrow a token from the sack, without blocking. |
| 283 |
|
| 284 |
Raises: |
| 285 |
WouldBlock: if no tokens are available. |
| 286 |
RuntimeError: if the current task already holds one of this sack's |
| 287 |
tokens. |
| 288 |
|
| 289 |
""" |
| 290 |
self.acquire_on_behalf_of_nowait(trio.lowlevel.current_task()) |
| 291 |
|
| 292 |
@enable_ki_protection |
| 293 |
def acquire_on_behalf_of_nowait(self, borrower: Task | object) -> None: |
| 294 |
"""Borrow a token from the sack on behalf of ``borrower``, without |
| 295 |
blocking. |
| 296 |
|
| 297 |
Args: |
| 298 |
borrower: A :class:`trio.lowlevel.Task` or arbitrary opaque object |
| 299 |
used to record who is borrowing this token. This is used by |
| 300 |
:func:`trio.to_thread.run_sync` to allow threads to "hold |
| 301 |
tokens", with the intention in the future of using it to `allow |
| 302 |
deadlock detection and other useful things |
| 303 |
<https://github.com/python-trio/trio/issues/182>`__ |
| 304 |
|
| 305 |
Raises: |
| 306 |
WouldBlock: if no tokens are available. |
| 307 |
RuntimeError: if ``borrower`` already holds one of this sack's |
| 308 |
tokens. |
| 309 |
|
| 310 |
""" |
| 311 |
if borrower in self._borrowers: |
| 312 |
raise RuntimeError( |
| 313 |
"this borrower is already holding one of this CapacityLimiter's tokens", |
| 314 |
) |
| 315 |
if len(self._borrowers) < self._total_tokens and not self._lot: |
| 316 |
self._borrowers.add(borrower) |
| 317 |
else: |
| 318 |
raise trio.WouldBlock |
| 319 |
|
| 320 |
@enable_ki_protection |
| 321 |
async def acquire(self) -> None: |
| 322 |
"""Borrow a token from the sack, blocking if necessary. |
| 323 |
|
| 324 |
Raises: |
| 325 |
RuntimeError: if the current task already holds one of this sack's |
| 326 |
tokens. |
| 327 |
|
| 328 |
""" |
| 329 |
await self.acquire_on_behalf_of(trio.lowlevel.current_task()) |
| 330 |
|
| 331 |
@enable_ki_protection |
| 332 |
async def acquire_on_behalf_of(self, borrower: Task | object) -> None: |
| 333 |
"""Borrow a token from the sack on behalf of ``borrower``, blocking if |
| 334 |
necessary. |
| 335 |
|
| 336 |
Args: |
| 337 |
borrower: A :class:`trio.lowlevel.Task` or arbitrary opaque object |
| 338 |
used to record who is borrowing this token; see |
| 339 |
:meth:`acquire_on_behalf_of_nowait` for details. |
| 340 |
|
| 341 |
Raises: |
| 342 |
RuntimeError: if ``borrower`` task already holds one of this sack's |
| 343 |
tokens. |
| 344 |
|
| 345 |
""" |
| 346 |
await trio.lowlevel.checkpoint_if_cancelled() |
| 347 |
try: |
| 348 |
self.acquire_on_behalf_of_nowait(borrower) |
| 349 |
except trio.WouldBlock: |
| 350 |
task = trio.lowlevel.current_task() |
| 351 |
self._pending_borrowers[task] = borrower |
| 352 |
try: |
| 353 |
await self._lot.park() |
| 354 |
except trio.Cancelled: |
| 355 |
self._pending_borrowers.pop(task) |
| 356 |
raise |
| 357 |
else: |
| 358 |
await trio.lowlevel.cancel_shielded_checkpoint() |
| 359 |
|
| 360 |
@enable_ki_protection |
| 361 |
def release(self) -> None: |
| 362 |
"""Put a token back into the sack. |
| 363 |
|
| 364 |
Raises: |
| 365 |
RuntimeError: if the current task has not acquired one of this |
| 366 |
sack's tokens. |
| 367 |
|
| 368 |
""" |
| 369 |
self.release_on_behalf_of(trio.lowlevel.current_task()) |
| 370 |
|
| 371 |
@enable_ki_protection |
| 372 |
def release_on_behalf_of(self, borrower: Task | object) -> None: |
| 373 |
"""Put a token back into the sack on behalf of ``borrower``. |
| 374 |
|
| 375 |
Raises: |
| 376 |
RuntimeError: if the given borrower has not acquired one of this |
| 377 |
sack's tokens. |
| 378 |
|
| 379 |
""" |
| 380 |
if borrower not in self._borrowers: |
| 381 |
raise RuntimeError( |
| 382 |
"this borrower isn't holding any of this CapacityLimiter's tokens", |
| 383 |
) |
| 384 |
self._borrowers.remove(borrower) |
| 385 |
self._wake_waiters() |
| 386 |
|
| 387 |
def statistics(self) -> CapacityLimiterStatistics: |
| 388 |
"""Return an object containing debugging information. |
| 389 |
|
| 390 |
Currently the following fields are defined: |
| 391 |
|
| 392 |
* ``borrowed_tokens``: The number of tokens currently borrowed from |
| 393 |
the sack. |
| 394 |
* ``total_tokens``: The total number of tokens in the sack. Usually |
| 395 |
this will be larger than ``borrowed_tokens``, but it's possibly for |
| 396 |
it to be smaller if :attr:`total_tokens` was recently decreased. |
| 397 |
* ``borrowers``: A list of all tasks or other entities that currently |
| 398 |
hold a token. |
| 399 |
* ``tasks_waiting``: The number of tasks blocked on this |
| 400 |
:class:`CapacityLimiter`\'s :meth:`acquire` or |
| 401 |
:meth:`acquire_on_behalf_of` methods. |
| 402 |
|
| 403 |
""" |
| 404 |
return CapacityLimiterStatistics( |
| 405 |
borrowed_tokens=len(self._borrowers), |
| 406 |
total_tokens=self._total_tokens, |
| 407 |
# Use a list instead of a frozenset just in case we start to allow |
| 408 |
# one borrower to hold multiple tokens in the future |
| 409 |
borrowers=list(self._borrowers), |
| 410 |
tasks_waiting=len(self._lot), |
| 411 |
) |
| 412 |
|
| 413 |
|
| 414 |
@final |
| 415 |
class Semaphore(AsyncContextManagerMixin): |
| 416 |
"""A `semaphore <https://en.wikipedia.org/wiki/Semaphore_(programming)>`__. |
| 417 |
|
| 418 |
A semaphore holds an integer value, which can be incremented by |
| 419 |
calling :meth:`release` and decremented by calling :meth:`acquire` – but |
| 420 |
the value is never allowed to drop below zero. If the value is zero, then |
| 421 |
:meth:`acquire` will block until someone calls :meth:`release`. |
| 422 |
|
| 423 |
If you're looking for a :class:`Semaphore` to limit the number of tasks |
| 424 |
that can access some resource simultaneously, then consider using a |
| 425 |
:class:`CapacityLimiter` instead. |
| 426 |
|
| 427 |
This object's interface is similar to, but different from, that of |
| 428 |
:class:`threading.Semaphore`. |
| 429 |
|
| 430 |
A :class:`Semaphore` object can be used as an async context manager; it |
| 431 |
blocks on entry but not on exit. |
| 432 |
|
| 433 |
Args: |
| 434 |
initial_value (int): A non-negative integer giving semaphore's initial |
| 435 |
value. |
| 436 |
max_value (int or None): If given, makes this a "bounded" semaphore that |
| 437 |
raises an error if the value is about to exceed the given |
| 438 |
``max_value``. |
| 439 |
|
| 440 |
""" |
| 441 |
|
| 442 |
def __init__(self, initial_value: int, *, max_value: int | None = None) -> None: |
| 443 |
if not isinstance(initial_value, int): |
| 444 |
raise TypeError("initial_value must be an int") |
| 445 |
if initial_value < 0: |
| 446 |
raise ValueError("initial value must be >= 0") |
| 447 |
if max_value is not None: |
| 448 |
if not isinstance(max_value, int): |
| 449 |
raise TypeError("max_value must be None or an int") |
| 450 |
if max_value < initial_value: |
| 451 |
raise ValueError("max_values must be >= initial_value") |
| 452 |
|
| 453 |
# Invariants: |
| 454 |
# bool(self._lot) implies self._value == 0 |
| 455 |
# (or equivalently: self._value > 0 implies not self._lot) |
| 456 |
self._lot = trio.lowlevel.ParkingLot() |
| 457 |
self._value = initial_value |
| 458 |
self._max_value = max_value |
| 459 |
|
| 460 |
def __repr__(self) -> str: |
| 461 |
if self._max_value is None: |
| 462 |
max_value_str = "" |
| 463 |
else: |
| 464 |
max_value_str = f", max_value={self._max_value}" |
| 465 |
return f"<trio.Semaphore({self._value}{max_value_str}) at {id(self):#x}>" |
| 466 |
|
| 467 |
@property |
| 468 |
def value(self) -> int: |
| 469 |
"""The current value of the semaphore.""" |
| 470 |
return self._value |
| 471 |
|
| 472 |
@property |
| 473 |
def max_value(self) -> int | None: |
| 474 |
"""The maximum allowed value. May be None to indicate no limit.""" |
| 475 |
return self._max_value |
| 476 |
|
| 477 |
@enable_ki_protection |
| 478 |
def acquire_nowait(self) -> None: |
| 479 |
"""Attempt to decrement the semaphore value, without blocking. |
| 480 |
|
| 481 |
Raises: |
| 482 |
WouldBlock: if the value is zero. |
| 483 |
|
| 484 |
""" |
| 485 |
if self._value > 0: |
| 486 |
assert not self._lot |
| 487 |
self._value -= 1 |
| 488 |
else: |
| 489 |
raise trio.WouldBlock |
| 490 |
|
| 491 |
@enable_ki_protection |
| 492 |
async def acquire(self) -> None: |
| 493 |
"""Decrement the semaphore value, blocking if necessary to avoid |
| 494 |
letting it drop below zero. |
| 495 |
|
| 496 |
""" |
| 497 |
await trio.lowlevel.checkpoint_if_cancelled() |
| 498 |
try: |
| 499 |
self.acquire_nowait() |
| 500 |
except trio.WouldBlock: |
| 501 |
await self._lot.park() |
| 502 |
else: |
| 503 |
await trio.lowlevel.cancel_shielded_checkpoint() |
| 504 |
|
| 505 |
@enable_ki_protection |
| 506 |
def release(self) -> None: |
| 507 |
"""Increment the semaphore value, possibly waking a task blocked in |
| 508 |
:meth:`acquire`. |
| 509 |
|
| 510 |
Raises: |
| 511 |
ValueError: if incrementing the value would cause it to exceed |
| 512 |
:attr:`max_value`. |
| 513 |
|
| 514 |
""" |
| 515 |
if self._lot: |
| 516 |
assert self._value == 0 |
| 517 |
self._lot.unpark(count=1) |
| 518 |
else: |
| 519 |
if self._max_value is not None and self._value == self._max_value: |
| 520 |
raise ValueError("semaphore released too many times") |
| 521 |
self._value += 1 |
| 522 |
|
| 523 |
def statistics(self) -> ParkingLotStatistics: |
| 524 |
"""Return an object containing debugging information. |
| 525 |
|
| 526 |
Currently the following fields are defined: |
| 527 |
|
| 528 |
* ``tasks_waiting``: The number of tasks blocked on this semaphore's |
| 529 |
:meth:`acquire` method. |
| 530 |
|
| 531 |
""" |
| 532 |
return self._lot.statistics() |
| 533 |
|
| 534 |
|
| 535 |
@attrs.frozen |
| 536 |
class LockStatistics: |
| 537 |
"""An object containing debugging information for a Lock. |
| 538 |
|
| 539 |
Currently the following fields are defined: |
| 540 |
|
| 541 |
* ``locked`` (boolean): indicating whether the lock is held. |
| 542 |
* ``owner``: the :class:`trio.lowlevel.Task` currently holding the lock, |
| 543 |
or None if the lock is not held. |
| 544 |
* ``tasks_waiting`` (int): The number of tasks blocked on this lock's |
| 545 |
:meth:`trio.Lock.acquire` method. |
| 546 |
|
| 547 |
""" |
| 548 |
|
| 549 |
locked: bool |
| 550 |
owner: Task | None |
| 551 |
tasks_waiting: int |
| 552 |
|
| 553 |
|
| 554 |
@attrs.define(eq=False, repr=False, slots=False) |
| 555 |
class _LockImpl(AsyncContextManagerMixin): |
| 556 |
_lot: ParkingLot = attrs.field(factory=ParkingLot, init=False) |
| 557 |
_owner: Task | None = attrs.field(default=None, init=False) |
| 558 |
|
| 559 |
def __repr__(self) -> str: |
| 560 |
if self.locked(): |
| 561 |
s1 = "locked" |
| 562 |
s2 = f" with {len(self._lot)} waiters" |
| 563 |
else: |
| 564 |
s1 = "unlocked" |
| 565 |
s2 = "" |
| 566 |
return f"<{s1} {self.__class__.__name__} object at {id(self):#x}{s2}>" |
| 567 |
|
| 568 |
def locked(self) -> bool: |
| 569 |
"""Check whether the lock is currently held. |
| 570 |
|
| 571 |
Returns: |
| 572 |
bool: True if the lock is held, False otherwise. |
| 573 |
|
| 574 |
""" |
| 575 |
return self._owner is not None |
| 576 |
|
| 577 |
@enable_ki_protection |
| 578 |
def acquire_nowait(self) -> None: |
| 579 |
"""Attempt to acquire the lock, without blocking. |
| 580 |
|
| 581 |
Raises: |
| 582 |
WouldBlock: if the lock is held. |
| 583 |
|
| 584 |
""" |
| 585 |
|
| 586 |
task = trio.lowlevel.current_task() |
| 587 |
if self._owner is task: |
| 588 |
raise RuntimeError("attempt to re-acquire an already held Lock") |
| 589 |
elif self._owner is None and not self._lot: |
| 590 |
# No-one owns it |
| 591 |
self._owner = task |
| 592 |
add_parking_lot_breaker(task, self._lot) |
| 593 |
else: |
| 594 |
raise trio.WouldBlock |
| 595 |
|
| 596 |
@enable_ki_protection |
| 597 |
async def acquire(self) -> None: |
| 598 |
"""Acquire the lock, blocking if necessary. |
| 599 |
|
| 600 |
Raises: |
| 601 |
BrokenResourceError: if the owner of the lock exits without releasing. |
| 602 |
""" |
| 603 |
await trio.lowlevel.checkpoint_if_cancelled() |
| 604 |
try: |
| 605 |
self.acquire_nowait() |
| 606 |
except trio.WouldBlock: |
| 607 |
try: |
| 608 |
# NOTE: it's important that the contended acquire path is just |
| 609 |
# "_lot.park()", because that's how Condition.wait() acquires the |
| 610 |
# lock as well. |
| 611 |
await self._lot.park() |
| 612 |
except trio.BrokenResourceError: |
| 613 |
raise trio.BrokenResourceError( |
| 614 |
f"Owner of this lock exited without releasing: {self._owner}", |
| 615 |
) from None |
| 616 |
else: |
| 617 |
await trio.lowlevel.cancel_shielded_checkpoint() |
| 618 |
|
| 619 |
@enable_ki_protection |
| 620 |
def release(self) -> None: |
| 621 |
"""Release the lock. |
| 622 |
|
| 623 |
Raises: |
| 624 |
RuntimeError: if the calling task does not hold the lock. |
| 625 |
|
| 626 |
""" |
| 627 |
task = trio.lowlevel.current_task() |
| 628 |
if task is not self._owner: |
| 629 |
raise RuntimeError("can't release a Lock you don't own") |
| 630 |
remove_parking_lot_breaker(self._owner, self._lot) |
| 631 |
if self._lot: |
| 632 |
(self._owner,) = self._lot.unpark(count=1) |
| 633 |
add_parking_lot_breaker(self._owner, self._lot) |
| 634 |
else: |
| 635 |
self._owner = None |
| 636 |
|
| 637 |
def statistics(self) -> LockStatistics: |
| 638 |
"""Return an object containing debugging information. |
| 639 |
|
| 640 |
Currently the following fields are defined: |
| 641 |
|
| 642 |
* ``locked``: boolean indicating whether the lock is held. |
| 643 |
* ``owner``: the :class:`trio.lowlevel.Task` currently holding the lock, |
| 644 |
or None if the lock is not held. |
| 645 |
* ``tasks_waiting``: The number of tasks blocked on this lock's |
| 646 |
:meth:`acquire` method. |
| 647 |
|
| 648 |
""" |
| 649 |
return LockStatistics( |
| 650 |
locked=self.locked(), |
| 651 |
owner=self._owner, |
| 652 |
tasks_waiting=len(self._lot), |
| 653 |
) |
| 654 |
|
| 655 |
|
| 656 |
@final |
| 657 |
class Lock(_LockImpl): |
| 658 |
"""A classic `mutex |
| 659 |
<https://en.wikipedia.org/wiki/Lock_(computer_science)>`__. |
| 660 |
|
| 661 |
This is a non-reentrant, single-owner lock. Unlike |
| 662 |
:class:`threading.Lock`, only the owner of the lock is allowed to release |
| 663 |
it. |
| 664 |
|
| 665 |
A :class:`Lock` object can be used as an async context manager; it |
| 666 |
blocks on entry but not on exit. |
| 667 |
|
| 668 |
""" |
| 669 |
|
| 670 |
|
| 671 |
@final |
| 672 |
class StrictFIFOLock(_LockImpl): |
| 673 |
r"""A variant of :class:`Lock` where tasks are guaranteed to acquire the |
| 674 |
lock in strict first-come-first-served order. |
| 675 |
|
| 676 |
An example of when this is useful is if you're implementing something like |
| 677 |
:class:`trio.SSLStream` or an HTTP/2 server using `h2 |
| 678 |
<https://hyper-h2.readthedocs.io/>`__, where you have multiple concurrent |
| 679 |
tasks that are interacting with a shared state machine, and at |
| 680 |
unpredictable moments the state machine requests that a chunk of data be |
| 681 |
sent over the network. (For example, when using h2 simply reading incoming |
| 682 |
data can occasionally `create outgoing data to send |
| 683 |
<https://http2.github.io/http2-spec/#PING>`__.) The challenge is to make |
| 684 |
sure that these chunks are sent in the correct order, without being |
| 685 |
garbled. |
| 686 |
|
| 687 |
One option would be to use a regular :class:`Lock`, and wrap it around |
| 688 |
every interaction with the state machine:: |
| 689 |
|
| 690 |
# This approach is sometimes workable but often sub-optimal; see below |
| 691 |
async with lock: |
| 692 |
state_machine.do_something() |
| 693 |
if state_machine.has_data_to_send(): |
| 694 |
await conn.sendall(state_machine.get_data_to_send()) |
| 695 |
|
| 696 |
But this can be problematic. If you're using h2 then *usually* reading |
| 697 |
incoming data doesn't create the need to send any data, so we don't want |
| 698 |
to force every task that tries to read from the network to sit and wait |
| 699 |
a potentially long time for ``sendall`` to finish. And in some situations |
| 700 |
this could even potentially cause a deadlock, if the remote peer is |
| 701 |
waiting for you to read some data before it accepts the data you're |
| 702 |
sending. |
| 703 |
|
| 704 |
:class:`StrictFIFOLock` provides an alternative. We can rewrite our |
| 705 |
example like:: |
| 706 |
|
| 707 |
# Note: no awaits between when we start using the state machine and |
| 708 |
# when we block to take the lock! |
| 709 |
state_machine.do_something() |
| 710 |
if state_machine.has_data_to_send(): |
| 711 |
# Notice that we fetch the data to send out of the state machine |
| 712 |
# *before* sleeping, so that other tasks won't see it. |
| 713 |
chunk = state_machine.get_data_to_send() |
| 714 |
async with strict_fifo_lock: |
| 715 |
await conn.sendall(chunk) |
| 716 |
|
| 717 |
First we do all our interaction with the state machine in a single |
| 718 |
scheduling quantum (notice there are no ``await``\s in there), so it's |
| 719 |
automatically atomic with respect to other tasks. And then if and only if |
| 720 |
we have data to send, we get in line to send it – and |
| 721 |
:class:`StrictFIFOLock` guarantees that each task will send its data in |
| 722 |
the same order that the state machine generated it. |
| 723 |
|
| 724 |
Currently, :class:`StrictFIFOLock` is identical to :class:`Lock`, |
| 725 |
but (a) this may not always be true in the future, especially if Trio ever |
| 726 |
implements `more sophisticated scheduling policies |
| 727 |
<https://github.com/python-trio/trio/issues/32>`__, and (b) the above code |
| 728 |
is relying on a pretty subtle property of its lock. Using a |
| 729 |
:class:`StrictFIFOLock` acts as an executable reminder that you're relying |
| 730 |
on this property. |
| 731 |
|
| 732 |
""" |
| 733 |
|
| 734 |
|
| 735 |
@attrs.frozen |
| 736 |
class ConditionStatistics: |
| 737 |
r"""An object containing debugging information for a Condition. |
| 738 |
|
| 739 |
Currently the following fields are defined: |
| 740 |
|
| 741 |
* ``tasks_waiting`` (int): The number of tasks blocked on this condition's |
| 742 |
:meth:`trio.Condition.wait` method. |
| 743 |
* ``lock_statistics``: The result of calling the underlying |
| 744 |
:class:`Lock`\s :meth:`~Lock.statistics` method. |
| 745 |
|
| 746 |
""" |
| 747 |
|
| 748 |
tasks_waiting: int |
| 749 |
lock_statistics: LockStatistics |
| 750 |
|
| 751 |
|
| 752 |
@final |
| 753 |
class Condition(AsyncContextManagerMixin): |
| 754 |
"""A classic `condition variable |
| 755 |
<https://en.wikipedia.org/wiki/Monitor_(synchronization)>`__, similar to |
| 756 |
:class:`threading.Condition`. |
| 757 |
|
| 758 |
A :class:`Condition` object can be used as an async context manager to |
| 759 |
acquire the underlying lock; it blocks on entry but not on exit. |
| 760 |
|
| 761 |
Args: |
| 762 |
lock (Lock): the lock object to use. If given, must be a |
| 763 |
:class:`trio.Lock`. If None, a new :class:`Lock` will be allocated |
| 764 |
and used. |
| 765 |
|
| 766 |
""" |
| 767 |
|
| 768 |
def __init__(self, lock: Lock | None = None) -> None: |
| 769 |
if lock is None: |
| 770 |
lock = Lock() |
| 771 |
if type(lock) is not Lock: |
| 772 |
raise TypeError("lock must be a trio.Lock") |
| 773 |
self._lock = lock |
| 774 |
self._lot = trio.lowlevel.ParkingLot() |
| 775 |
|
| 776 |
def locked(self) -> bool: |
| 777 |
"""Check whether the underlying lock is currently held. |
| 778 |
|
| 779 |
Returns: |
| 780 |
bool: True if the lock is held, False otherwise. |
| 781 |
|
| 782 |
""" |
| 783 |
return self._lock.locked() |
| 784 |
|
| 785 |
def acquire_nowait(self) -> None: |
| 786 |
"""Attempt to acquire the underlying lock, without blocking. |
| 787 |
|
| 788 |
Raises: |
| 789 |
WouldBlock: if the lock is currently held. |
| 790 |
|
| 791 |
""" |
| 792 |
return self._lock.acquire_nowait() |
| 793 |
|
| 794 |
async def acquire(self) -> None: |
| 795 |
"""Acquire the underlying lock, blocking if necessary. |
| 796 |
|
| 797 |
Raises: |
| 798 |
BrokenResourceError: if the owner of the underlying lock exits without releasing. |
| 799 |
""" |
| 800 |
await self._lock.acquire() |
| 801 |
|
| 802 |
def release(self) -> None: |
| 803 |
"""Release the underlying lock.""" |
| 804 |
self._lock.release() |
| 805 |
|
| 806 |
@enable_ki_protection |
| 807 |
async def wait(self) -> None: |
| 808 |
"""Wait for another task to call :meth:`notify` or |
| 809 |
:meth:`notify_all`. |
| 810 |
|
| 811 |
When calling this method, you must hold the lock. It releases the lock |
| 812 |
while waiting, and then re-acquires it before waking up. |
| 813 |
|
| 814 |
There is a subtlety with how this method interacts with cancellation: |
| 815 |
when cancelled it will block to re-acquire the lock before raising |
| 816 |
:exc:`Cancelled`. This may cause cancellation to be less prompt than |
| 817 |
expected. The advantage is that it makes code like this work:: |
| 818 |
|
| 819 |
async with condition: |
| 820 |
await condition.wait() |
| 821 |
|
| 822 |
If we didn't re-acquire the lock before waking up, and :meth:`wait` |
| 823 |
were cancelled here, then we'd crash in ``condition.__aexit__`` when |
| 824 |
we tried to release the lock we no longer held. |
| 825 |
|
| 826 |
Raises: |
| 827 |
RuntimeError: if the calling task does not hold the lock. |
| 828 |
BrokenResourceError: if the owner of the lock exits without releasing, when attempting to re-acquire. |
| 829 |
|
| 830 |
""" |
| 831 |
if trio.lowlevel.current_task() is not self._lock._owner: |
| 832 |
raise RuntimeError("must hold the lock to wait") |
| 833 |
self.release() |
| 834 |
# NOTE: we go to sleep on self._lot, but we'll wake up on |
| 835 |
# self._lock._lot. That's all that's required to acquire a Lock. |
| 836 |
try: |
| 837 |
await self._lot.park() |
| 838 |
except: |
| 839 |
with trio.CancelScope(shield=True): |
| 840 |
await self.acquire() |
| 841 |
raise |
| 842 |
|
| 843 |
def notify(self, n: int = 1) -> None: |
| 844 |
"""Wake one or more tasks that are blocked in :meth:`wait`. |
| 845 |
|
| 846 |
Args: |
| 847 |
n (int): The number of tasks to wake. |
| 848 |
|
| 849 |
Raises: |
| 850 |
RuntimeError: if the calling task does not hold the lock. |
| 851 |
|
| 852 |
""" |
| 853 |
if trio.lowlevel.current_task() is not self._lock._owner: |
| 854 |
raise RuntimeError("must hold the lock to notify") |
| 855 |
self._lot.repark(self._lock._lot, count=n) |
| 856 |
|
| 857 |
def notify_all(self) -> None: |
| 858 |
"""Wake all tasks that are currently blocked in :meth:`wait`. |
| 859 |
|
| 860 |
Raises: |
| 861 |
RuntimeError: if the calling task does not hold the lock. |
| 862 |
|
| 863 |
""" |
| 864 |
if trio.lowlevel.current_task() is not self._lock._owner: |
| 865 |
raise RuntimeError("must hold the lock to notify") |
| 866 |
self._lot.repark_all(self._lock._lot) |
| 867 |
|
| 868 |
def statistics(self) -> ConditionStatistics: |
| 869 |
r"""Return an object containing debugging information. |
| 870 |
|
| 871 |
Currently the following fields are defined: |
| 872 |
|
| 873 |
* ``tasks_waiting``: The number of tasks blocked on this condition's |
| 874 |
:meth:`wait` method. |
| 875 |
* ``lock_statistics``: The result of calling the underlying |
| 876 |
:class:`Lock`\s :meth:`~Lock.statistics` method. |
| 877 |
|
| 878 |
""" |
| 879 |
return ConditionStatistics( |
| 880 |
tasks_waiting=len(self._lot), |
| 881 |
lock_statistics=self._lock.statistics(), |
| 882 |
) |