Python 如何终止asyncio协程(不是第一个完成的案例)

Python 如何终止asyncio协程(不是第一个完成的案例),python,python-3.x,python-asyncio,future,concurrent.futures,Python,Python 3.x,Python Asyncio,Future,Concurrent.futures,有一个例子:maincoroutine创建需要很长时间才能完成的coroutine,这意味着FIRST\u COMPLETED案例无法访问。问题:考虑到wait asyncio.wait(tasks)行本身会阻塞所有内容,如何访问挂起的未来集 import asyncio async def worker(i): #some big work await asyncio.sleep(100000) async def main(): tasks = [asyncio.

有一个例子:
main
coroutine创建需要很长时间才能完成的coroutine,这意味着
FIRST\u COMPLETED
案例无法访问。问题:考虑到
wait asyncio.wait(tasks)
行本身会阻塞所有内容,如何访问挂起的未来集

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())

如何避免等待阻塞和杀死某些协同程序?例如4?

您可以创建另一个任务来监视您的任务:

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)
    # ...

我真的不明白你的问题,如果你不想等待一个任务完成,为什么要使用
asyncio。等等?要开始执行任务,你不需要它,它们会在你创建它们时立即开始。这对我不起作用,因为如果不等待,当父koroutine完成时,所有子koroutine都会中断