繁体   English   中英

Python 中的异步/等待和同步方式的结果没有区别

[英]No difference in result between async/await and synchronous way in Python

我写了以下代码:

import asyncio

async def write_after(pause,text):
  print('begin')
  await asyncio.sleep(pause)
  print(text)

async def main():
  await write_after(1,'Hello...')
  await write_after(2,'...world')

asyncio.run(main())

结果我得到:

begin
Hello...
begin
...world

begin之后有停顿。 我想知道为什么结果不是:

begin
begin
Hello...
...world

就像执行使用任务的程序一样。

基本上发生的事情是您正在等待第一个结果完成,然后开始第二个 function 调用并等待该结果。 我想你所期待的是这样的:

import asyncio

async def write_after(pause,text):
  print('begin')
  await asyncio.sleep(pause)
  print(text)

async def main():
  await asyncio.gather(
    write_after(1,'Hello...'),
    write_after(2,'...world')
  )

asyncio.run(main())

这将同时启动两个协程并等待每个协程的结果。 结果将是:

begin
begin
Hello...
...world

@kingkupps 分析是正确的。 不幸的是,myy asyncio模块没有run方法(Python 3.7),因此作为替代方案:

import asyncio

async def write_after(pause,text):
  print('begin')
  await asyncio.sleep(pause)
  print(text)

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(
        asyncio.gather(
            write_after(1, 'Hello'),
            write_after(2, '...world')
        )
    )

main()

印刷:

begin
begin
Hello
...world

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM