| 1 |
# ParkingLot provides an abstraction for a fair waitqueue with cancellation |
| 2 |
# and requeuing support. Inspiration: |
| 3 |
# |
| 4 |
# https://webkit.org/blog/6161/locking-in-webkit/ |
| 5 |
# https://amanieu.github.io/parking_lot/ |
| 6 |
# |
| 7 |
# which were in turn heavily influenced by |
| 8 |
# |
| 9 |
# http://gee.cs.oswego.edu/dl/papers/aqs.pdf |
| 10 |
# |
| 11 |
# Compared to these, our use of cooperative scheduling allows some |
| 12 |
# simplifications (no need for internal locking). On the other hand, the need |
| 13 |
# to support Trio's strong cancellation semantics adds some complications |
| 14 |
# (tasks need to know where they're queued so they can cancel). Also, in the |
| 15 |
# above work, the ParkingLot is a global structure that holds a collection of |
| 16 |
# waitqueues keyed by lock address, and which are opportunistically allocated |
| 17 |
# and destroyed as contention arises; this allows the worst-case memory usage |
| 18 |
# for all waitqueues to be O(#tasks). Here we allocate a separate wait queue |
| 19 |
# for each synchronization object, so we're O(#objects + #tasks). This isn't |
| 20 |
# *so* bad since compared to our synchronization objects are heavier than |
| 21 |
# theirs and our tasks are lighter, so for us #objects is smaller and #tasks |
| 22 |
# is larger. |
| 23 |
# |
| 24 |
# This is in the core because for two reasons. First, it's used by |
| 25 |
# UnboundedQueue, and UnboundedQueue is used for a number of things in the |
| 26 |
# core. And second, it's responsible for providing fairness to all of our |
| 27 |
# high-level synchronization primitives (locks, queues, etc.). For now with |
| 28 |
# our FIFO scheduler this is relatively trivial (it's just a FIFO waitqueue), |
| 29 |
# but in the future we ever start support task priorities or fair scheduling |
| 30 |
# |
| 31 |
# https://github.com/python-trio/trio/issues/32 |
| 32 |
# |
| 33 |
# then all we'll have to do is update this. (Well, full-fledged task |
| 34 |
# priorities might also require priority inheritance, which would require more |
| 35 |
# work.) |
| 36 |
# |
| 37 |
# For discussion of data structures to use here, see: |
| 38 |
# |
| 39 |
# https://github.com/dabeaz/curio/issues/136 |
| 40 |
# |
| 41 |
# (and also the articles above). Currently we use a SortedDict ordered by a |
| 42 |
# global monotonic counter that ensures FIFO ordering. The main advantage of |
| 43 |
# this is that it's easy to implement :-). An intrusive doubly-linked list |
| 44 |
# would also be a natural approach, so long as we only handle FIFO ordering. |
| 45 |
# |
| 46 |
# XX: should we switch to the shared global ParkingLot approach? |
| 47 |
# |
| 48 |
# XX: we should probably add support for "parking tokens" to allow for |
| 49 |
# task-fair RWlock (basically: when parking a task needs to be able to mark |
| 50 |
# itself as a reader or a writer, and then a task-fair wakeup policy is, wake |
| 51 |
# the next task, and if it's a reader than keep waking tasks so long as they |
| 52 |
# are readers). Without this I think you can implement write-biased or |
| 53 |
# read-biased RWlocks (by using two parking lots and drawing from whichever is |
| 54 |
# preferred), but not task-fair -- and task-fair plays much more nicely with |
| 55 |
# WFQ. (Consider what happens in the two-lot implementation if you're |
| 56 |
# write-biased but all the pending writers are blocked at the scheduler level |
| 57 |
# by the WFQ logic...) |
| 58 |
# ...alternatively, "phase-fair" RWlocks are pretty interesting: |
| 59 |
# http://www.cs.unc.edu/~anderson/papers/ecrts09b.pdf |
| 60 |
# Useful summary: |
| 61 |
# https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html |
| 62 |
# |
| 63 |
# XX: if we do add WFQ, then we might have to drop the current feature where |
| 64 |
# unpark returns the tasks that were unparked. Rationale: suppose that at the |
| 65 |
# time we call unpark, the next task is deprioritized... and then, before it |
| 66 |
# becomes runnable, a new task parks which *is* runnable. Ideally we should |
| 67 |
# immediately wake the new task, and leave the old task on the queue for |
| 68 |
# later. But this means we can't commit to which task we are unparking when |
| 69 |
# unpark is called. |
| 70 |
# |
| 71 |
# See: https://github.com/python-trio/trio/issues/53 |
| 72 |
from __future__ import annotations |
| 73 |
|
| 74 |
import inspect |
| 75 |
import math |
| 76 |
from collections import OrderedDict |
| 77 |
from typing import TYPE_CHECKING |
| 78 |
|
| 79 |
import attrs |
| 80 |
import outcome |
| 81 |
|
| 82 |
from .. import _core |
| 83 |
from .._util import final |
| 84 |
|
| 85 |
if TYPE_CHECKING: |
| 86 |
from collections.abc import Iterator |
| 87 |
|
| 88 |
from ._run import Task |
| 89 |
|
| 90 |
|
| 91 |
GLOBAL_PARKING_LOT_BREAKER: dict[Task, list[ParkingLot]] = {} |
| 92 |
|
| 93 |
|
| 94 |
def add_parking_lot_breaker(task: Task, lot: ParkingLot) -> None: |
| 95 |
"""Register a task as a breaker for a lot. See :meth:`ParkingLot.break_lot`. |
| 96 |
|
| 97 |
raises: |
| 98 |
trio.BrokenResourceError: if the task has already exited. |
| 99 |
""" |
| 100 |
if inspect.getcoroutinestate(task.coro) == inspect.CORO_CLOSED: |
| 101 |
raise _core._exceptions.BrokenResourceError( |
| 102 |
"Attempted to add already exited task as lot breaker.", |
| 103 |
) |
| 104 |
if task not in GLOBAL_PARKING_LOT_BREAKER: |
| 105 |
GLOBAL_PARKING_LOT_BREAKER[task] = [lot] |
| 106 |
else: |
| 107 |
GLOBAL_PARKING_LOT_BREAKER[task].append(lot) |
| 108 |
|
| 109 |
|
| 110 |
def remove_parking_lot_breaker(task: Task, lot: ParkingLot) -> None: |
| 111 |
"""Deregister a task as a breaker for a lot. See :meth:`ParkingLot.break_lot`""" |
| 112 |
try: |
| 113 |
GLOBAL_PARKING_LOT_BREAKER[task].remove(lot) |
| 114 |
except (KeyError, ValueError): |
| 115 |
raise RuntimeError( |
| 116 |
"Attempted to remove task as breaker for a lot it is not registered for", |
| 117 |
) from None |
| 118 |
if not GLOBAL_PARKING_LOT_BREAKER[task]: |
| 119 |
del GLOBAL_PARKING_LOT_BREAKER[task] |
| 120 |
|
| 121 |
|
| 122 |
@attrs.frozen |
| 123 |
class ParkingLotStatistics: |
| 124 |
"""An object containing debugging information for a ParkingLot. |
| 125 |
|
| 126 |
Currently, the following fields are defined: |
| 127 |
|
| 128 |
* ``tasks_waiting`` (int): The number of tasks blocked on this lot's |
| 129 |
:meth:`trio.lowlevel.ParkingLot.park` method. |
| 130 |
|
| 131 |
""" |
| 132 |
|
| 133 |
tasks_waiting: int |
| 134 |
|
| 135 |
|
| 136 |
@final |
| 137 |
@attrs.define(eq=False) |
| 138 |
class ParkingLot: |
| 139 |
"""A fair wait queue with cancellation and requeuing. |
| 140 |
|
| 141 |
This class encapsulates the tricky parts of implementing a wait |
| 142 |
queue. It's useful for implementing higher-level synchronization |
| 143 |
primitives like queues and locks. |
| 144 |
|
| 145 |
In addition to the methods below, you can use ``len(parking_lot)`` to get |
| 146 |
the number of parked tasks, and ``if parking_lot: ...`` to check whether |
| 147 |
there are any parked tasks. |
| 148 |
|
| 149 |
""" |
| 150 |
|
| 151 |
# {task: None}, we just want a deque where we can quickly delete random |
| 152 |
# items |
| 153 |
_parked: OrderedDict[Task, None] = attrs.field(factory=OrderedDict, init=False) |
| 154 |
broken_by: list[Task] = attrs.field(factory=list, init=False) |
| 155 |
|
| 156 |
def __len__(self) -> int: |
| 157 |
"""Returns the number of parked tasks.""" |
| 158 |
return len(self._parked) |
| 159 |
|
| 160 |
def __bool__(self) -> bool: |
| 161 |
"""True if there are parked tasks, False otherwise.""" |
| 162 |
return bool(self._parked) |
| 163 |
|
| 164 |
# XX this currently returns None |
| 165 |
# if we ever add the ability to repark while one's resuming place in |
| 166 |
# line (for false wakeups), then we could have it return a ticket that |
| 167 |
# abstracts the "place in line" concept. |
| 168 |
@_core.enable_ki_protection |
| 169 |
async def park(self) -> None: |
| 170 |
"""Park the current task until woken by a call to :meth:`unpark` or |
| 171 |
:meth:`unpark_all`. |
| 172 |
|
| 173 |
Raises: |
| 174 |
BrokenResourceError: if attempting to park in a broken lot, or the lot |
| 175 |
breaks before we get to unpark. |
| 176 |
|
| 177 |
""" |
| 178 |
if self.broken_by: |
| 179 |
raise _core.BrokenResourceError( |
| 180 |
f"Attempted to park in parking lot broken by {self.broken_by}", |
| 181 |
) |
| 182 |
task = _core.current_task() |
| 183 |
self._parked[task] = None |
| 184 |
task.custom_sleep_data = self |
| 185 |
|
| 186 |
def abort_fn(_: _core.RaiseCancelT) -> _core.Abort: |
| 187 |
del task.custom_sleep_data._parked[task] |
| 188 |
return _core.Abort.SUCCEEDED |
| 189 |
|
| 190 |
await _core.wait_task_rescheduled(abort_fn) |
| 191 |
|
| 192 |
def _pop_several(self, count: int | float) -> Iterator[Task]: # noqa: PYI041 |
| 193 |
if isinstance(count, float): |
| 194 |
if math.isinf(count): |
| 195 |
count = len(self._parked) |
| 196 |
else: |
| 197 |
raise ValueError("Cannot pop a non-integer number of tasks.") |
| 198 |
else: |
| 199 |
count = min(count, len(self._parked)) |
| 200 |
for _ in range(count): |
| 201 |
task, _ = self._parked.popitem(last=False) |
| 202 |
yield task |
| 203 |
|
| 204 |
@_core.enable_ki_protection |
| 205 |
def unpark(self, *, count: int | float = 1) -> list[Task]: # noqa: PYI041 |
| 206 |
"""Unpark one or more tasks. |
| 207 |
|
| 208 |
This wakes up ``count`` tasks that are blocked in :meth:`park`. If |
| 209 |
there are fewer than ``count`` tasks parked, then wakes as many tasks |
| 210 |
are available and then returns successfully. |
| 211 |
|
| 212 |
Args: |
| 213 |
count (int | math.inf): the number of tasks to unpark. |
| 214 |
|
| 215 |
""" |
| 216 |
tasks = list(self._pop_several(count)) |
| 217 |
for task in tasks: |
| 218 |
_core.reschedule(task) |
| 219 |
return tasks |
| 220 |
|
| 221 |
def unpark_all(self) -> list[Task]: |
| 222 |
"""Unpark all parked tasks.""" |
| 223 |
return self.unpark(count=len(self)) |
| 224 |
|
| 225 |
@_core.enable_ki_protection |
| 226 |
def repark( |
| 227 |
self, |
| 228 |
new_lot: ParkingLot, |
| 229 |
*, |
| 230 |
count: int | float = 1, # noqa: PYI041 |
| 231 |
) -> None: |
| 232 |
"""Move parked tasks from one :class:`ParkingLot` object to another. |
| 233 |
|
| 234 |
This dequeues ``count`` tasks from one lot, and requeues them on |
| 235 |
another, preserving order. For example:: |
| 236 |
|
| 237 |
async def parker(lot): |
| 238 |
print("sleeping") |
| 239 |
await lot.park() |
| 240 |
print("woken") |
| 241 |
|
| 242 |
async def main(): |
| 243 |
lot1 = trio.lowlevel.ParkingLot() |
| 244 |
lot2 = trio.lowlevel.ParkingLot() |
| 245 |
async with trio.open_nursery() as nursery: |
| 246 |
nursery.start_soon(parker, lot1) |
| 247 |
await trio.testing.wait_all_tasks_blocked() |
| 248 |
assert len(lot1) == 1 |
| 249 |
assert len(lot2) == 0 |
| 250 |
lot1.repark(lot2) |
| 251 |
assert len(lot1) == 0 |
| 252 |
assert len(lot2) == 1 |
| 253 |
# This wakes up the task that was originally parked in lot1 |
| 254 |
lot2.unpark() |
| 255 |
|
| 256 |
If there are fewer than ``count`` tasks parked, then reparks as many |
| 257 |
tasks as are available and then returns successfully. |
| 258 |
|
| 259 |
Args: |
| 260 |
new_lot (ParkingLot): the parking lot to move tasks to. |
| 261 |
count (int|math.inf): the number of tasks to move. |
| 262 |
|
| 263 |
""" |
| 264 |
if not isinstance(new_lot, ParkingLot): |
| 265 |
raise TypeError("new_lot must be a ParkingLot") |
| 266 |
for task in self._pop_several(count): |
| 267 |
new_lot._parked[task] = None |
| 268 |
task.custom_sleep_data = new_lot |
| 269 |
|
| 270 |
def repark_all(self, new_lot: ParkingLot) -> None: |
| 271 |
"""Move all parked tasks from one :class:`ParkingLot` object to |
| 272 |
another. |
| 273 |
|
| 274 |
See :meth:`repark` for details. |
| 275 |
|
| 276 |
""" |
| 277 |
return self.repark(new_lot, count=len(self)) |
| 278 |
|
| 279 |
def break_lot(self, task: Task | None = None) -> None: |
| 280 |
"""Break this lot, with ``task`` noted as the task that broke it. |
| 281 |
|
| 282 |
This causes all parked tasks to raise an error, and any |
| 283 |
future tasks attempting to park to error. Unpark & repark become no-ops as the |
| 284 |
parking lot is empty. |
| 285 |
|
| 286 |
The error raised contains a reference to the task sent as a parameter. The task |
| 287 |
is also saved in the parking lot in the ``broken_by`` attribute. |
| 288 |
""" |
| 289 |
if task is None: |
| 290 |
task = _core.current_task() |
| 291 |
|
| 292 |
# if lot is already broken, just mark this as another breaker and return |
| 293 |
if self.broken_by: |
| 294 |
self.broken_by.append(task) |
| 295 |
return |
| 296 |
|
| 297 |
self.broken_by.append(task) |
| 298 |
|
| 299 |
for parked_task in self._parked: |
| 300 |
_core.reschedule( |
| 301 |
parked_task, |
| 302 |
outcome.Error( |
| 303 |
_core.BrokenResourceError(f"Parking lot broken by {task}"), |
| 304 |
), |
| 305 |
) |
| 306 |
self._parked.clear() |
| 307 |
|
| 308 |
def statistics(self) -> ParkingLotStatistics: |
| 309 |
"""Return an object containing debugging information. |
| 310 |
|
| 311 |
Currently the following fields are defined: |
| 312 |
|
| 313 |
* ``tasks_waiting``: The number of tasks blocked on this lot's |
| 314 |
:meth:`park` method. |
| 315 |
|
| 316 |
""" |
| 317 |
return ParkingLotStatistics(tasks_waiting=len(self._parked)) |