| 1 |
import trio |
| 2 |
|
| 3 |
|
| 4 |
__all__ = ["race_events"] |
| 5 |
|
| 6 |
|
| 7 |
# Based on https://trio.readthedocs.io/en/stable/reference-core.html#custom-supervisors |
| 8 |
|
| 9 |
|
| 10 |
async def jockey(event: trio.Event, cancel_scope: trio.CancelScope) -> None: |
| 11 |
await event.wait() |
| 12 |
cancel_scope.cancel() |
| 13 |
|
| 14 |
|
| 15 |
async def race_events(*events: trio.Event) -> None: |
| 16 |
""" |
| 17 |
Wait for any of the given events to be set. |
| 18 |
|
| 19 |
Args: |
| 20 |
*events: The events to wait for. |
| 21 |
|
| 22 |
""" |
| 23 |
if not events: |
| 24 |
raise ValueError("no events provided") |
| 25 |
|
| 26 |
try: |
| 27 |
async with trio.open_nursery() as nursery: |
| 28 |
for event in events: |
| 29 |
nursery.start_soon(jockey, event, nursery.cancel_scope) |
| 30 |
except BaseExceptionGroup as exc: |
| 31 |
try: |
| 32 |
trio._util.raise_single_exception_from_group(exc) |
| 33 |
except trio._util.MultipleExceptionError: |
| 34 |
raise AssertionError( |
| 35 |
"race_events should be canceled; please file a bug report" |
| 36 |
) from exc |