Skip to main content
 首页 » 编程设计

python之异步 : keep multiple coroutines running

2025年02月15日7rubylouvre

我有多个协程需要同时(永远)运行。对于错误处理,其中一个例程偶尔会结束并需要重新生成,我使用了以下代码,但它假定需要重新启动的是 coroutine1。

pending = {coroutine1(), coroutine2()} 
while True: 
    a = asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) 
    done, pending = loop.run_until_complete(a) 
    pending = pending | {coroutine1()} 

我怎样才能以更好、更通用的方式解决这个问题?

请您参考如下方法:

使用不同的方法怎么样?

async def run_forever(corofn): 
    while True: 
        await corofn() 
 
corofns = coroutine1, coroutine2 
await asyncio.wait(map(run_forever, corofns))