首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么大多数异步示例使用loop.run_until_complete()?

为什么大多数异步示例使用loop.run_until_complete()?
EN

Stack Overflow用户
提问于 2016-10-20 07:46:47
回答 2查看 66.2K关注 0票数 54

我浏览了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_futureloop.run_forever()的组合来并发运行多个协同例程。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-25 02:58:55

run_until_complete被用来运行未来,直到它完成。它将阻止后面的代码的执行。但是,它确实会导致事件循环运行。任何已调度的期货都将一直运行,直到传递给run_until_complete的未来完成。

在这个例子中:

代码语言:javascript
运行
复制
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将运行。您的输出将是:

代码语言:javascript
运行
复制
io start
io end
doing other things

如果在运行do_io之前使用事件循环调度do_other_things,则当do_io等待时,控制将从do_other_things切换到前者。

代码语言:javascript
运行
复制
loop.create_task(do_other_things())
loop.run_until_complete(do_io())

这将得到以下内容的输出:

代码语言:javascript
运行
复制
doing other things
io start
io end

这是因为do_other_things被安排在do_io之前。有很多不同的方法可以获得相同的输出,但哪一种方法真正有意义取决于您的应用程序实际做了什么。因此,我将把它作为练习留给读者。

票数 70
EN

Stack Overflow用户

发布于 2021-01-05 22:45:13

我想大多数人都不了解create_task。当你使用create_taskensure_future时,它已经被安排好了。

代码语言:javascript
运行
复制
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())

结果是

代码语言:javascript
运行
复制
time0 
print hello 
time0+1 
print world 
time0+2

但如果你不等待task1,做一些别的事情

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
time0
print hello
time0+2
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40143289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档