使用asyncio.Queue进行生产者-消费者流

时间:2018-09-30 22:29:59

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

我对如何将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来向消费者表明生产已经完成。

1 个答案:

答案 0 :(得分:6)

  

如何修改上面的程序,以便生产者可以自己与消费者/工人同时安排协程?

可以在不更改其基本逻辑的情况下对该示例进行概括:

  • 将插入循环移动到单独的生产者协程。
  • 在后台启动消费者,让他们处理生产的商品。
  • 等待生产者完成await的制作,例如await producer()await gather(*producers)等。
  • 所有生产者完成后,等待用await queue.join()处理剩余的生产项目
  • 取消消费者,所有消费者现在都在闲着等待下一个永远不会到达的排队商品。

以下是实现上述内容的示例:

import asyncio, random, time

async def rnd_sleep(t):
    # sleep for T seconds on average
    await asyncio.sleep(t * random.random() * 2)

async def producer(queue):
    while True:
        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()
        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())
相关问题