【问题标题】:Using asyncio.Queue for producer-consumer flow使用 asyncio.Queue 进行生产者-消费者流
【发布时间】:2019-03-06 01:35:01
【问题描述】:

我很困惑如何将asyncio.Queue 用于特定的生产者-消费者模式,其中生产者和消费者同时独立运行。

首先,考虑这个例子,它紧跟docs for asyncio.Queue

import asyncio
import random
import time

async def worker(name, queue):
    while True:
        sleep_for = await queue.get()
        await asyncio.sleep(sleep_for)
        queue.task_done()
        print(f'{name} has slept for {sleep_for:0.2f} seconds')

async def main(n):
    queue = asyncio.Queue()
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)
    tasks = []
    for i in range(n):
        task = asyncio.create_task(worker(f'worker-{i}', queue))
        tasks.append(task)
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)
    print('====')
    print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
    print(f'total expected sleep time: {total_sleep_time:.2f} seconds')

if __name__ == '__main__':
    import sys
    n = 3 if len(sys.argv) == 1 else sys.argv[1]
    asyncio.run(main())

这个脚本有一个更详细的细节:项目被同步放入队列中,queue.put_nowait(sleep_for) 通过传统的 for 循环。

我的目标是创建一个使用async def worker()(或consumer())和async def producer() 的脚本。两者都应安排为同时运行。没有一个消费者协程与生产者明确绑定或链接。

如何修改上面的程序,使生产者成为自己的协程,可以与消费者/工作者同时调度?


PYMOTW 有第二个例子。它要求生产者提前知道消费者的数量,并使用None作为生产完成的信号给消费者。

【问题讨论】:

    标签: python python-3.x async-await python-asyncio


    【解决方案1】:

    如何修改上面的程序,使生产者成为自己的协程,可以与消费者/工作者同时调度?

    这个例子可以在不改变其基本逻辑的情况下推广:

    • 将插入循环移至单独的生产者协程。
    • 在后台启动消费者,让他们在生产项目时对其进行处理。
    • 随着消费者的运行,启动生产者并等待他们完成生产项目,如await producer()await gather(*producers) 等。
    • 所有生产者完成后,等待消费者使用await queue.join() 处理剩余的项目。
    • 取消消费者,所有消费者现在都在等待队列交付下一个项目,因为我们知道生产者已经完成,所以下一个项目永远不会到达。

    这是一个实现上述内容的示例:

    import asyncio, random
     
    async def rnd_sleep(t):
        # sleep for T seconds on average
        await asyncio.sleep(t * random.random() * 2)
     
    async def producer(queue):
        while True:
            # produce a token and send it to a consumer
            token = random.random()
            print(f'produced {token}')
            if token < .05:
                break
            await queue.put(token)
            await rnd_sleep(.1)
     
    async def consumer(queue):
        while True:
            token = await queue.get()
            # process the token received from a producer
            await rnd_sleep(.3)
            queue.task_done()
            print(f'consumed {token}')
     
    async def main():
        queue = asyncio.Queue()
     
        # fire up the both producers and consumers
        producers = [asyncio.create_task(producer(queue))
                     for _ in range(3)]
        consumers = [asyncio.create_task(consumer(queue))
                     for _ in range(10)]
     
        # with both producers and consumers running, wait for
        # the producers to finish
        await asyncio.gather(*producers)
        print('---- done producing')
     
        # wait for the remaining tasks to be processed
        await queue.join()
     
        # cancel the consumers, which are now idle
        for c in consumers:
            c.cancel()
     
    asyncio.run(main())
    

    请注意,在现实生活中的生产者和消费者中,尤其是那些涉及网络访问的生产者和消费者中,您可能希望捕获处理过程中发生的与 IO 相关的异常。如果异常是可恢复的,就像大多数与网络相关的异常一样,您可以简单地捕获异常并记录错误。您仍然应该调用task_done(),否则queue.join() 将由于未处理的项目而挂起。如果重新尝试处理该项目有意义,您可以在调用task_done() 之前将其返回到队列中。例如:

    # like the above, but handling exceptions during processing:
    async def consumer(queue):
        while True:
            token = await queue.get()
            try:
                # this uses aiohttp or whatever
                await process(token)
            except aiohttp.ClientError as e:
                print(f"Error processing token {token}: {e}")
                # If it makes sense, return the token to the queue to be
                # processed again. (You can use a counter to avoid
                # processing a faulty token infinitely.)
                #await queue.put(token)
            queue.task_done()
            print(f'consumed {token}')
    

    【讨论】:

    • 我正在用 aiohttpaiofiles 写关于 asyncio 的文章,并想在一个部分中提及队列 --- 你介意我链接到并引用这个答案吗?
    • @BradSolomon 当然,继续!
    • 我正在尝试调整它以测试目录中是否存在文件,但它似乎并没有异步地交错生产者和消费者。首先生成所有生产者,然后是消费者。如何修改它以在if pathlib.Path().exists(): ...等cpu绑定进程上工作。
    • @pylang 如果您的代码受 CPU 限制(或以其他方式阻塞 asyncio 未处理),asyncio 不会自动交错。在这种情况下,使用run_in_executor 将阻塞代码卸载到线程池。然后你会写if await loop.run_in_executor(None, lambda: pathlib.Path(...).exists()): ...
    • @CpILL 当然,你可以这样做(这就是“假设异常是可恢复的”所指的),只要记住无论如何也要调用task_done,以便当前的出列被计为已解决。队列不会介意您读取了同一个对象,它只会计算入队和出队的数量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多