[英]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.