Sam*_*elN 23 python-3.x python-asyncio
我正在阅读Python文档asyncio,我想知道为什么大多数示例使用loop.run_until_complete()而不是Asyncio.ensure_future().
例如:https://docs.python.org/dev/library/asyncio-task.html
似乎ensure_future是一种更好的方式来展示非阻塞函数的优点.run_until_complete另一方面,像同步函数一样阻塞循环.
这让我觉得我应该使用run_until_complete而不是组合ensure_future使用loop.run_forever()来同时运行多个协同例程.
dir*_*irn 29
run_until_complete用于运行未来直到它完成.它将阻止其后面的代码执行.但是,它会导致事件循环运行.任何已经安排的期货都将运行,直到未来run_until_complete完成.
鉴于这个例子:
import asyncio
async def do_io():
print('io start')
await asyncio.sleep(5)
print('io end')
async def do_other_things():
print('doing other things')
loop = asyncio.get_event_loop()
loop.run_until_complete(do_io())
loop.run_until_complete(do_other_things())
loop.close()
Run Code Online (Sandbox Code Playgroud)
do_io会跑.完成后,do_other_things将运行.你的输出将是:
io start
io end
doing other things
Run Code Online (Sandbox Code Playgroud)
如果您do_other_things在运行之前使用事件循环进行计划,则do_io控制将从前一个等待时切换do_io到do_other_things.
loop.create_task(do_other_things())
loop.run_until_complete(do_io())
Run Code Online (Sandbox Code Playgroud)
这将获得以下输出:
doing other things
io start
io end
Run Code Online (Sandbox Code Playgroud)
这是因为do_other_things之前安排的do_io.有很多不同的方法可以获得相同的输出,但哪一个有意义实际上取决于您的应用程序实际执行的操作.所以我将把它作为练习留给读者.
小智 14
我想大多数人都没有理解create_task。当您create_task或 时ensure_future,它已经被安排了。
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello')) # not block here
task2 = asyncio.create_task(
say_after(2, 'world'))
print(f"started at {time.strftime('%X')}") # time0
await task1 # block here!
print(f"finished at {time.strftime('%X')}")
await task2 # block here!
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
结果是
time0
print hello
time0+1
print world
time0+2
Run Code Online (Sandbox Code Playgroud)
但如果您不等待任务1,请做其他事情
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello')) # not block here
print(f"finished at {time.strftime('%X')}") # time0
await asyncio.sleep(2) # not await task1
print(f"finished at {time.strftime('%X')}") # time0+2
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
它仍然会执行任务1
time0
print hello
time0+2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17578 次 |
| 最近记录: |