-1

There is an example: main coroutine creates coroutines that take a long time to complete, what means FIRST_COMPLETED case is unreachable. Problem: considering that await asyncio.wait(tasks) line blocks everything under itself, how to get access to pending futures set?

import asyncio

async def worker(i):
    #some big work
    await asyncio.sleep(100000)

async def main():
    tasks = [asyncio.create_task(worker(i), name=str(i)) for i in range(5)]
    done, pending = await asyncio.wait(tasks) #or asyncio.as_completed(tasks, return_when=FIRST_COMPLETED) no matter
    # everything below is unreachable until tasks are in process
    # we want to kill certain task
    for future in pending:
        if future.get_name == "4":
            future.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

How to avoid await block and kill certain coroutine? for example 4?

kostya
  • 27
  • 7

1 Answers1

0

You can create another task to monitor your tasks:

async def monitor(tasks):
    # monitor the state of tasks and cancel some
    while not all(t.done() for t in tasks):
        for t in tasks:
            if not t.done() and t.get_name() == "4":
                t.cancel()
            # ...
        # give the tasks some time to make progress
        await asyncio.sleep(1)

async def main():
    tasks = [asyncio.create_task(worker(i), name=str(i)) for i in range(5)]
    tasks.append(asyncio.create_task(monitor(tasks[:])))
    done, pending = await asyncio.wait(tasks)
    # ...
user4815162342
  • 141,790
  • 18
  • 296
  • 355