Jiv*_*van 3 python asynchronous event-loop python-3.x python-asyncio
使用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()
Run Code Online (Sandbox Code Playgroud)
预期输出:
$ 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
Run Code Online (Sandbox Code Playgroud)
这工作正常:
记:你想等待快速非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)
Run Code Online (Sandbox Code Playgroud)
time.sleep本身是阻塞的,不能很好地与await.
| 归档时间: |
|
| 查看次数: |
10203 次 |
| 最近记录: |