对没有 sleep() 的代码使用异步是不是有意义?

Posted

技术标签:

【中文标题】对没有 sleep() 的代码使用异步是不是有意义?【英文标题】:Does it make sense to use async with code that has no sleep()?对没有 sleep() 的代码使用异步是否有意义? 【发布时间】:2021-02-07 11:51:46 【问题描述】:

我已经阅读了很多解释 Python 中的 async 的不同文章。但是他们都举了asyncio.sleep(x)的例子,比如这个:

import asyncio

async def test1 ():
    await asyncio.sleep(1)
    print(1)

async def test2 ():
    print(2)

async def main ():
    await asyncio.gather(test1(), test2())

asyncio.run(main()) #prints 2, then 1

在这种情况下,对我来说一切都很清楚:函数 test1 中的 await 表示在执行 asyncio.sleep 期间我们可以做其他事情,例如执行函数 test2。

我不明白的是,如果我不在我的代码中使用睡眠,那么异步如何有用?在这种情况下如何同时运行函数?比如下例中如何同时运行函数test1和test2?

import asyncio
import time

async def calculate (a):
    return a**a

async def test1 ():
    x = await calculate(1111111)
    print('done!')

async def test2 ():
    for i in range(100):
        print('.', end='')

async def main ():
    await asyncio.gather(test1(), test2())

asyncio.run(main()) #prints 'done!' before the dots

【问题讨论】:

asynciogreat 当你有代码需要等待的事情。就像网络响应,或者某些事件的发生,比如电子邮件已经到达。每个await 都是其他代码运行的机会,代码不再需要等待。 我要补充一点,以yield 结尾的每条awaits 链(例如,await some_future 归结为这一点。)是异步执行代码的机会。如果您 await 的函数不使用 await 使用 asyncio 功能的函数,例如asyncio.sleep(),但只是返回一个结果,那么在这种情况下,asyncio 没有任何好处。 【参考方案1】:

您可以通过任务实现此目的。

任务用于同时调度协程。

当一个协程被包装到一个具有类似asyncio.create_task()(见official documentation)函数的任务中时,协程会自动安排在不久的将来运行:

import asyncio
import time


async def calculate(a):
    return a**a


async def test1():
    # Schedule calculate(a) to run soon concurrently
    # with "main()".
    task = asyncio.create_task(calculate(11111))

    # "task" can now be used to cancel "calculate(a)", or
    # can simply be awaited to wait until it is complete:
    await task
    print('done!')


async def dots_printer():
    for i in range(100):
        print('.', end='')
        

async def test2():
    # Schedule dots_printer() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(dots_printer())

    # "task" can now be used to cancel "dots_printer()", or
    # can simply be awaited to wait until it is complete:
    await task


async def main():
    await asyncio.gather(test1(), test2())


asyncio.run(main()) #prints the dots before 'done!'

【讨论】:

以上是关于对没有 sleep() 的代码使用异步是不是有意义?的主要内容,如果未能解决你的问题,请参考以下文章

多个异步调用,如何以有意义的方式处理响应

可以使用 Task.WhenAll(...) 或其他比每次等待更有意义的东西重写此异步/等待代码吗? [复制]

使用 JSLint 并遵循它是不是有意义? [关闭]

将 Psyco 与 django 一起使用是不是有意义?

缩小 NodeJS 中使用的代码是不是有意义?

使用 XSLT 创建网站是不是有意义 [关闭]