两个异步任务 - 一个依赖于 Python 中的另一个



我需要编写一个代码,我需要实时检查某个变量的状态。我建议使用asyncio来创建两个异步 def 函数

import asyncio
async def one():
global flag
flag = True
while flag == True:
await asyncio.sleep(0.2)
print("Doing one")
async def two():
await asyncio.sleep(2)
global flag
flag = False
async def main():
tasks = []
tasks.append(one())
tasks.append(two())
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
print("Loop ended")

当循环启动时,所有任务都已启动,2秒后def two()设置flag=Falsedef one()停止。这很好,但我希望def one()在没有await asyncio.sleep(0.2)的情况下循环执行,因为我不想有真正的实时更新,所以我设置了await asyncio.sleep(0.0). 这是一种好的做法吗?

使用全局变量确实是一种不好的做法。你要找的是asyncio的原语,特别是asyncio.Event原语。这是您正在做的事情,但asyncio.Event

import asyncio
async def one(event):
while event.is_set() == False:
await asyncio.sleep(0.5)
print("Hello World!")
async def two(event):
await asyncio.sleep(2)
event.set()
async def main():
event = asyncio.Event()
await asyncio.gather(*[one(event), two(event)])
asyncio.run(main())

最新更新