我需要编写一个代码,在其中我需要实时检查某些变量的状态。我决定使用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")
开始循环时,所有任务已启动,def two()
设置2秒后flag=False
停止def one()
。很好,但是我希望def one()
执行while循环而没有await asyncio.sleep(0.2)
,因为我不想进行实时更新,所以我设置了await asyncio.sleep(0.0)
。
这是个好习惯吗?
答案 0 :(得分:2)
使用全局变量确实是不好的做法。您正在寻找的是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())