python 使用asyncio的生产者/消费者示例。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用asyncio的生产者/消费者示例。相关的知识,希望对你有一定的参考价值。

import asyncio
import random
# import uvloop  # makes asyncio 2-4 times faster
# asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

# Async
async def produce(queue, n):
    for x in range(1, n + 1):
        # produce an item
        print('producing {}/{}'.format(x, n))
        # simulate i/o operation using sleep
        await asyncio.sleep(random.random())
        item = str(x)
        # put the item in the queue
        await queue.put(item)

    # indicate the producer is done
    await queue.put(None)


async def consume(queue):
    while True:
        # wait for an item from the producer
        item = await queue.get()
        if item is None:
            # the producer emits None to indicate that it is done
            break

        # process the item
        print('consuming item {}...'.format(item))
        # simulate i/o operation using sleep
        await asyncio.sleep(random.random())


loop = asyncio.get_event_loop()
queue = asyncio.Queue(loop=loop)
producer_coro = produce(queue, 10)
consumer_coro = consume(queue)
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()

以上是关于python 使用asyncio的生产者/消费者示例。的主要内容,如果未能解决你的问题,请参考以下文章

python 异步编程

python多线程编程-queue模块和生产者-消费者问题

Python yield关键字实现生产者和消费者

Asyncio:带有 aio-pika 的 Fastapi,消费者忽略 Await

disruptor

Python 生产者与消费者模型