我浏览了asyncio
的Python文档,我想知道为什么大多数示例使用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()
的组合来并发运行多个协同例程。
发布于 2016-10-25 02:58:55
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()
do_io
将运行。完成后,do_other_things
将运行。您的输出将是:
io start
io end
doing other things
如果在运行do_io
之前使用事件循环调度do_other_things
,则当do_io
等待时,控制将从do_other_things
切换到前者。
loop.create_task(do_other_things())
loop.run_until_complete(do_io())
这将得到以下内容的输出:
doing other things
io start
io end
这是因为do_other_things
被安排在do_io
之前。有很多不同的方法可以获得相同的输出,但哪一种方法真正有意义取决于您的应用程序实际做了什么。因此,我将把它作为练习留给读者。
发布于 2021-01-05 22:45:13
我想大多数人都不了解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())
结果是
time0
print hello
time0+1
print world
time0+2
但如果你不等待task1,做一些别的事情
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())
它将仍然执行task1
time0
print hello
time0+2
https://stackoverflow.com/questions/40143289
复制相似问题