Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor waiting for tasks to complete from task group on the asyncio backend #854

Merged
merged 6 commits into from
Jan 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 13 additions & 21 deletions src/anyio/_backends/_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,26 +701,6 @@ def started(self, value: T_contra | None = None) -> None:
_task_states[task].parent_id = self._parent_id


async def _wait(tasks: Iterable[asyncio.Task[object]]) -> None:
tasks = set(tasks)
waiter = get_running_loop().create_future()

def on_completion(task: asyncio.Task[object]) -> None:
tasks.discard(task)
if not tasks and not waiter.done():
waiter.set_result(None)

for task in tasks:
task.add_done_callback(on_completion)
del task

try:
await waiter
finally:
while tasks:
tasks.pop().remove_done_callback(on_completion)


if sys.version_info >= (3, 12):
_eager_task_factory_code: CodeType | None = asyncio.eager_task_factory.__code__
else:
Expand All @@ -733,6 +713,7 @@ def __init__(self) -> None:
self._active = False
self._exceptions: list[BaseException] = []
self._tasks: set[asyncio.Task] = set()
self._on_completed_fut: asyncio.Future[None] | None = None

async def __aenter__(self) -> TaskGroup:
self.cancel_scope.__enter__()
Expand All @@ -751,12 +732,15 @@ async def __aexit__(
if not isinstance(exc_val, CancelledError):
self._exceptions.append(exc_val)

loop = get_running_loop()
try:
if self._tasks:
with CancelScope() as wait_scope:
while self._tasks:
self._on_completed_fut = loop.create_future()

try:
await _wait(self._tasks)
await self._on_completed_fut
except CancelledError as exc:
# Shield the scope against further cancellation attempts,
# as they're not productive (#695)
Expand All @@ -771,6 +755,8 @@ async def __aexit__(
and not is_anyio_cancellation(exc)
):
exc_val = exc

self._on_completed_fut = None
agronholm marked this conversation as resolved.
Show resolved Hide resolved
else:
# If there are no child tasks to wait on, run at least one checkpoint
# anyway
Expand Down Expand Up @@ -808,6 +794,12 @@ def task_done(_task: asyncio.Task) -> None:
self._tasks.remove(task)
del _task_states[_task]

if self._on_completed_fut is not None and not self._tasks:
try:
self._on_completed_fut.set_result(None)
except asyncio.InvalidStateError:
pass

try:
exc = _task.exception()
except CancelledError as e:
Expand Down
Loading