【发布时间】:2016-12-30 15:24:42
【问题描述】:
使用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
【问题讨论】:
-
那么你得到的是什么输出呢?
BaseEventLoop不是具体的循环实现;使用asyncio.get_event_loop()为您的平台获取具体循环。 -
另外,
list操作不可等待。time.sleep()不会屈服于其他协程。
标签: python python-3.x asynchronous python-asyncio event-loop