异步任务可以排队吗

时间:2021-03-02 10:06:57

标签: python python-asyncio

我想要一个与以下类似的代码:

async def func(user_response):
 #does_something

while condition:
 #waits for a response from the user
 #await func(response from user)

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

我试过了:

async def func(user_response):
 #does_something

while condition:
 #waits for a response from the user
 #asyncio.create_task(response from user)

然而,我发现的问题是,如果用户响应两次,这两个功能将同时执行(当我基本上是排队时)。

1 个答案:

答案 0 :(得分:0)

<块引用>

异步任务是否可以排队

是的,您可以为此使用 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)