使用async/await在Python语言中并行执行两个异步循环的好方法是什么
我已经考虑过类似下面的代码,但不能理解在这种情况下如何使用async/await/EventLoop。
import asyncio
my_list = []
def notify():
length = len(my_list)
print("List has changed!", length)
async def append_task():
while True:
time.sleep(1)
await my_list.append(random.random())
notify()
async def pop_task():
while True:
time.sleep(1.8)
await my_list.pop()
notify()
loop = asyncio.get_event_loop()
loop.create_task(append_task())
loop.create_task(pop_task())
loop.run_forever()预期输出:
$ python prog.py
List has changed! 1 # after 1sec
List has changed! 0 # after 1.8sec
List has changed! 1 # after 2sec
List has changed! 2 # after 3sec
List has changed! 1 # after 3.6sec
List has changed! 2 # after 4sec
List has changed! 3 # after 5sec
List has changed! 2 # after 5.4sec发布于 2016-12-30 23:32:09
这可以很好地工作:
注意:您希望等待快速的非io绑定操作(甚至不是协程的list.append和list.pop );您可以做的是awaitasyncio.sleep(...) (这是一个协程,并将控制权返回给调用者):
import asyncio
import random
my_list = []
def notify():
length = len(my_list)
print("List has changed!", length)
async def append_task():
while True:
await asyncio.sleep(1)
my_list.append(random.random())
notify()
async def pop_task():
while True:
await asyncio.sleep(1.8)
my_list.pop()
notify()
loop = asyncio.get_event_loop()
cors = asyncio.wait([append_task(), pop_task()])
loop.run_until_complete(cors)time.sleep本身是阻塞的,并且不能很好地与await配合使用。
发布于 2016-12-30 23:33:14
List对象没有可等待的操作,也不需要等待,因为没有I/O或其他可以异步处理的延迟。
您还希望使用asyncio.sleep(),而不是time.sleep();后面的代码块。
下面的代码运行得很好;我在notify中添加了一个时间戳,以便更好地显示这一点:
from datetime import datetime
# ...
start = datetime.now()
def notify():
length = len(my_list)
print("t: {:.1f}, List has changed! {}".format(
(datetime.now() - start).total_seconds(), length))
async def append_task():
while True:
await asyncio.sleep(1)
my_list.append(random.random())
notify()
async def pop_task():
while True:
await asyncio.sleep(1.8)
my_list.pop()
notify()注意,我们在asyncio.sleep()调用上使用了await;这提供了一个点,在这个点上,您的协程(协作例程)将控制权交给另一个例程。
这会产生以下结果:
$ python asyncio_demo.py
t: 1.0, List has changed! 1
t: 1.8, List has changed! 0
t: 2.0, List has changed! 1
t: 3.0, List has changed! 2
t: 3.6, List has changed! 1
t: 4.0, List has changed! 2
t: 5.0, List has changed! 3
t: 5.4, List has changed! 2
t: 6.0, List has changed! 3https://stackoverflow.com/questions/41398596
复制相似问题