[英]two async tasks - one depends on another in python
I need to write a code where i need to to check in real time a status of some variable.我需要编写一个代码来实时检查某个变量的状态。 I decited to use asyncio
to create two async def functions我决定使用asyncio
创建两个 async 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")
When loop starts, all tasks has been lauched and after 2 seconds def two()
sets flag=False
, which stops def one()
.当循环开始时,所有任务都已启动,并且在 2 秒后def two()
设置flag=False
,这将停止def one()
。 It's good but i want def one()
to perform while loop without await asyncio.sleep(0.2)
becouse i dont want to have real live update so i set await asyncio.sleep(0.0)
.这很好,但我希望def one()
在没有await asyncio.sleep(0.2)
的情况下执行 while 循环,因为我不想进行真正的实时更新,所以我设置await asyncio.sleep(0.0)
。 Is it a good practice?这是一个好习惯吗?
Using a global variable is indeed bad practice.使用全局变量确实是不好的做法。 What you are looking for is asyncio
's primitives, specifically theasyncio.Event
primitive.您正在寻找的是asyncio
的原语,特别是asyncio.Event
原语。 Here is what you are doing, but with 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.