如何在不同进程中同时 运行 两个 asyncio 循环?

How can I run two asyncio loops simultaneously in different processes?

我一直在尝试 运行 两个并行的 asyncio 循环,但我没有找到关于如何这样做的有意义的说明。我想同时执行两个异步函数,而它们都依赖于一个全局变量。

我的代码如下所示:

import asyncio

#a---------------------------------------------------------------
async def foo(n):
    print("Executing foo(n)")
    return n**2

async def main_a():
    print("Executing main_a()")
    n = await foo(3)
    return n+1 
    
x = 1

async def periodic_a():
    global x
    i = 0
    while True:
        i += 2
        x = await main_a()
        x += i
        await asyncio.sleep(1)

#b-----------------------------------------------------------------

async def periodic_b():
    global x
    while True:
        print(f"There are {x} ducks in the pond")
        await asyncio.sleep(5)

#execution---------------------------------------------------------
loop = asyncio.get_event_loop()
task = loop.create_task(periodic_a())

try:
    loop.run_until_complete(task)
except asyncio.CancelledError:
    pass
except KeyboardInterrupt:
    task.cancel()
    loop.close()
    pass

我正在尝试同时将函数 periodic_aperiodic_b 获取到 运行,并每五秒提供一次 print(f"There are {x} ducks in the pond") 的输出。预先感谢您的帮助!

您应该为每个要同时 运行 的函数创建两个任务,然后用 asyncio.gather 等待它们。另请注意,您应该使用 asyncio.run 而不是直接使用事件循环,这将使您的代码更清晰,因为它会为您处理创建和关闭循环。修改代码的执行部分如下:

async def main():
    periodic_a_task = asyncio.create_task(periodic_a())
    periodic_b_task = asyncio.create_task(periodic_b())
    await asyncio.gather(periodic_a_task, periodic_b_task)

asyncio.run(main())

另请注意,您提到了多个进程,但在您描述的示例中不需要使用多进程。如果您确实需要多处理,您将需要一种不同的方法来处理具有共享内存的全局数据。