异步任务是否可以排队



我想有一个类似的代码如下:

async def func(user_response):
#does_something
while condition:
#waits for a response from the user
#await func(response from user)

但是,我希望它在函数执行时等待用户的另一个响应。

I have try:

async def func(user_response):
#does_something
while condition:
#waits for a response from the user
#asyncio.create_task(response from user)

然而,我发现的问题是,如果用户响应两次,两个函数将同时执行(当我将它们本质上排队时)。

异步任务可以排队吗

是的,你可以使用asyncio.Queue来达到这个目的:

async def func(user_response):
#does_something
async def worker(queue):
while True:
user_response = await queue.get()
await func(user_response)
async def main():
queue = asyncio.Queue()
# spawn the worker in the "background"
asyncio.create_task(worker(queue))
while condition:
#waits for a response from the user
# enqueue the response to be handled by the worker
await queue.put(user_response)

最新更新