简体   繁体   English

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

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

I've been trying to run two asyncio loops in parallel, but I am failing to find meaningful instruction on how to do so.我一直在尝试并行运行两个 asyncio 循环,但我未能找到有关如何执行此操作的有意义的说明。 I want to execute two async functions at the same time, while both of them depend on one global variable.我想同时执行两个异步函数,而它们都依赖于一个全局变量。

My code looks something like the following:我的代码如下所示:

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

I am trying to get functions periodic_a and periodic_b to run at the same time, and provide the output of print(f"There are {x} ducks in the pond") every five seconds.我试图让函数periodic_aperiodic_b同时运行,并每五秒提供一次print(f"There are {x} ducks in the pond")的 output。 Thank you in advance for any help!预先感谢您的任何帮助!

You should create two tasks for each function you want to run concurrently and then await them with asyncio.gather .您应该为每个要同时运行的 function 创建两个任务,然后使用asyncio.gather等待它们。 Also note you should use asyncio.run instead of using the event loop directly, this will make your code cleaner as it handles creating and shutting down the loop for you.另请注意,您应该使用asyncio.run而不是直接使用事件循环,这将使您的代码更清晰,因为它会为您处理创建和关闭循环。 Modify the execute section of your code the the following:修改代码的执行部分如下:

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

Also note you mention multiple processes, but there isn't any need to use multiprocessing in the example you're describing.另请注意,您提到了多个进程,但在您描述的示例中不需要使用 multiprocessing 。 If you do need multiprocessing, you'll need a different approach for global data with shared memory.如果您确实需要多处理,您将需要一种不同的方法来处理共享 memory 的全局数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM