| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from collections import defaultdict |
| 4 |
from contextlib import asynccontextmanager |
| 5 |
from typing import TYPE_CHECKING |
| 6 |
|
| 7 |
import attrs |
| 8 |
|
| 9 |
from .. import Event, _core, _util |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from collections.abc import AsyncIterator |
| 13 |
|
| 14 |
|
| 15 |
@_util.final |
| 16 |
@attrs.define(eq=False, slots=False) |
| 17 |
class Sequencer: |
| 18 |
"""A convenience class for forcing code in different tasks to run in an |
| 19 |
explicit linear order. |
| 20 |
|
| 21 |
Instances of this class implement a ``__call__`` method which returns an |
| 22 |
async context manager. The idea is that you pass a sequence number to |
| 23 |
``__call__`` to say where this block of code should go in the linear |
| 24 |
sequence. Block 0 starts immediately, and then block N doesn't start until |
| 25 |
block N-1 has finished. |
| 26 |
|
| 27 |
Example: |
| 28 |
An extremely elaborate way to print the numbers 0-5, in order:: |
| 29 |
|
| 30 |
async def worker1(seq): |
| 31 |
async with seq(0): |
| 32 |
print(0) |
| 33 |
async with seq(4): |
| 34 |
print(4) |
| 35 |
|
| 36 |
async def worker2(seq): |
| 37 |
async with seq(2): |
| 38 |
print(2) |
| 39 |
async with seq(5): |
| 40 |
print(5) |
| 41 |
|
| 42 |
async def worker3(seq): |
| 43 |
async with seq(1): |
| 44 |
print(1) |
| 45 |
async with seq(3): |
| 46 |
print(3) |
| 47 |
|
| 48 |
async def main(): |
| 49 |
seq = trio.testing.Sequencer() |
| 50 |
async with trio.open_nursery() as nursery: |
| 51 |
nursery.start_soon(worker1, seq) |
| 52 |
nursery.start_soon(worker2, seq) |
| 53 |
nursery.start_soon(worker3, seq) |
| 54 |
|
| 55 |
""" |
| 56 |
|
| 57 |
_sequence_points: defaultdict[int, Event] = attrs.field( |
| 58 |
factory=lambda: defaultdict(Event), |
| 59 |
init=False, |
| 60 |
) |
| 61 |
_claimed: set[int] = attrs.field(factory=set, init=False) |
| 62 |
_broken: bool = attrs.field(default=False, init=False) |
| 63 |
|
| 64 |
@asynccontextmanager |
| 65 |
async def __call__(self, position: int) -> AsyncIterator[None]: |
| 66 |
if position in self._claimed: |
| 67 |
raise RuntimeError(f"Attempted to reuse sequence point {position}") |
| 68 |
if self._broken: |
| 69 |
raise RuntimeError("sequence broken!") |
| 70 |
self._claimed.add(position) |
| 71 |
if position != 0: |
| 72 |
try: |
| 73 |
await self._sequence_points[position].wait() |
| 74 |
except _core.Cancelled: |
| 75 |
self._broken = True |
| 76 |
for event in self._sequence_points.values(): |
| 77 |
event.set() |
| 78 |
raise RuntimeError( |
| 79 |
"Sequencer wait cancelled -- sequence broken", |
| 80 |
) from None |
| 81 |
else: |
| 82 |
if self._broken: |
| 83 |
raise RuntimeError("sequence broken!") |
| 84 |
try: |
| 85 |
yield |
| 86 |
finally: |
| 87 |
self._sequence_points[position + 1].set() |