我有一個主函式,我用它運行,asyncio然后在它里面我用來event_loop.run_in_executor()運行一個阻塞函式的多個行程。
我希望做的是在這些行程中的每一個中為每個行程運行一個新的 asyncio 回圈,以便執行異步代碼。
所以我有一個主要的 async 函式,我在其中創建了多個行程,我想在每個行程中創建一個新的 asyncio 回圈。如何才能做到這一點?
uj5u.com熱心網友回復:
您可以asyncio.run使用協程在您的子行程中呼叫您想要執行的異步作業。一個最小的例子,它啟動 5 個行程,每個行程都有自己的事件回圈:
import asyncio
from concurrent.futures import ProcessPoolExecutor
def run_loop_in_process():
async def subprocess_async_work():
await asyncio.sleep(5) #whatever async code you need
asyncio.run(subprocess_async_work())
async def main():
loop = asyncio.get_running_loop()
pool = ProcessPoolExecutor()
tasks = [loop.run_in_executor(pool, run_loop_in_process) for _ in range(5)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344612.html
上一篇:為什么.then()在使用時不需要async關鍵字(類似于await)?Javascript如何知道這是一個異步操作?
