2

我是 Python 新手,代码类似于以下内容:

import time
import asyncio

async def my_async_function(i):
    print("My function {}".format(i))

async def start():
    requests = []

    # Create multiple requests
    for i in range(5):
        print("Creating request #{}".format(i))
        requests.append(my_async_function(i))

    # Do some additional work here
    print("Begin sleep")
    time.sleep(10)
    print("End sleep")

    # Wait for all requests to finish
    return await asyncio.gather(*requests)

asyncio.run(start())

无论“额外工作”需要多长时间,请求似乎只在“结束睡眠”之后运行。我猜asyncio.gather是什么实际上开始执行它们。我怎样才能让请求(又名my_async_function())立即开始,做额外的工作,然后等待最后完成?

编辑: 根据 Krumelur 的评论和我自己的发现,我正在寻找以下结果:

import time
import asyncio
import random

async def my_async_function(i):
    print("Begin function {}".format(i))
    await asyncio.sleep(int(random.random() * 10))
    print("End function {}".format(i))

async def start():
    requests = []

    # Create multiple requests
    for i in range(10):
        print("Creating request #{}".format(i))
        requests.append(asyncio.create_task(my_async_function(i)))

    # Do some additional work here
    print("Begin sleep")
    await asyncio.sleep(5)
    print("End sleep")

    # Wait for all requests to finish
    return await asyncio.gather(*requests)

asyncio.run(start())

这仅my_async_function在“附加工作”都可以等待的情况下才有效,以便事件循环可以为它们中的每一个提供执行时间。你需要create_task(如果你知道它是一个协程)或ensure_future(如果它可能是一个协程或未来)允许请求立即运行,否则它们仍然只有在你gather.

4

1 回答 1

0

time.sleep()是同步操作

你会想要使用异步睡眠并等待它,例如

await asyncio.sleep(10)

其他异步代码仅在当前任务产生时才会运行(即通常在“等待”某事时)。

使用异步代码意味着您必须在任何地方继续使用异步。异步操作适用于 I/O-bound 应用程序。如果“额外工作”主要受 CPU 限制,那么最好使用线程(但要注意全局解释器锁!)

于 2020-06-11T21:02:14.597 回答