Coverage for gcsfs/concurrency.py: 100%
11 statements
« prev ^ index » next coverage.py v7.9.1, created at 2026-04-20 18:41 -0400
« prev ^ index » next coverage.py v7.9.1, created at 2026-04-20 18:41 -0400
1import asyncio
2from contextlib import asynccontextmanager
5@asynccontextmanager
6async def parallel_tasks_first_completed(coros):
7 """
8 Starts coroutines in parallel and enters the context as soon as
9 at least one task has completed. Automatically cancels pending tasks
10 when exiting the context.
11 """
12 tasks = [asyncio.create_task(c) for c in coros]
13 try:
14 # Suspend until the first task finishes for maximum responsiveness
15 done, pending = await asyncio.wait(
16 set(tasks), return_when=asyncio.FIRST_COMPLETED
17 )
18 yield tasks, done, pending
19 finally:
20 # Ensure 'losing' tasks are cancelled immediately
21 for t in tasks:
22 if not t.done():
23 t.cancel()