小编use*_*694的帖子

asyncio模块如何工作,为什么我的更新样本同步运行?

我在Python 3.6中为asyncio尝试了以下代码:示例1:

import asyncio
import time

async def hello():

    print('hello')
    await asyncio.sleep(1)
    print('hello again')

tasks=[hello(),hello()]    
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)

输出符合预期:

hello
hello
hello again
hello again
Run Code Online (Sandbox Code Playgroud)

然后我想将asyncio.sleep更改为另一个def:

async def sleep():
    time.sleep(1)

async def hello():

    print('hello')
    await sleep()
    print('hello again')


tasks=[hello(),hello()]    
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)

输出:

hello
hello again
hello
hello again
Run Code Online (Sandbox Code Playgroud)

它似乎不是以异步模式运行,而是以正常同步模式运行.

问题是:为什么它不是以异步模式运行?如何将旧的同步模块更改为"异步"模块?

python async-await python-asyncio

2
推荐指数
1
解决办法
385
查看次数

标签 统计

async-await ×1

python ×1

python-asyncio ×1