asyncio队列多生产者(同步)单消费者
创始人
2024-09-21 06:30:17
0

下面是一个使用asyncio实现的多生产者(同步)单消费者的示例代码:

import asyncio
import random

async def producer(queue):
    while True:
        # 模拟一些生产的任务
        await asyncio.sleep(random.random())
        item = random.randint(1, 100)
        await queue.put(item)
        print(f'生产者放入队列: {item}')

async def consumer(queue):
    while True:
        # 模拟一些消费的任务
        await asyncio.sleep(random.random())
        item = await queue.get()
        print(f'消费者从队列取出: {item}')
        queue.task_done()

async def main():
    queue = asyncio.Queue()
    producers = [asyncio.create_task(producer(queue)) for _ in range(3)]
    consumer_task = asyncio.create_task(consumer(queue))

    # 等待所有生产者完成
    await asyncio.gather(*producers)

    # 等待队列中的任务全部完成
    await queue.join()

    consumer_task.cancel()
    await consumer_task

asyncio.run(main())

在这个示例中,我们创建了一个asyncio队列,并创建了多个生产者任务和一个消费者任务。生产者任务循环执行,每次生产一个随机数并放入队列中。消费者任务循环执行,每次从队列中取出一个元素并进行处理。在生产者任务完成后,我们使用await queue.join()等待队列中的所有任务都完成,然后取消消费者任务。最后,我们使用asyncio.run(main())来运行主任务。

相关内容

热门资讯

透视辅助!hhpoker透视脚... 透视辅助!hhpoker透视脚本,wepoker透视版下载,我来教大家(有挂透明)1、这是跨平台的黑...
透视app!wpk透视辅助方法... 透视app!wpk透视辅助方法,德普之星辅助功能如何打开,传递经验(有挂规律)1、下载好wpk透视辅...
透视教学!hhpoker透视脚... 透视教学!hhpoker透视脚本视频,红龙poker透视,每日必看推荐(有挂教学);1、游戏颠覆性的...
透视软件!wpk透视脚本下载,... 透视软件!wpk透视脚本下载,hhpoker透视脚本下载,最新通报(有挂技巧);1、ai机器人多个强...
透视免费!hhpoker辅助器... 透视免费!hhpoker辅助器,德普之星辅助器,盘点一款(有挂规律)1、起透看视 透明视辅助2、随意...
透视辅助!德普之星辅助功能如何... 透视辅助!德普之星辅助功能如何打开,aapoker辅助挂,实测必看(有挂教学)1、很好的工具软件,可...
透视模拟器!智星德州有脚本吗,... 透视模拟器!智星德州有脚本吗,wepoker免费透视脚本,重大通报(有挂了解)1、任何ai辅助神器的...
透视美元局!aapoker辅助... 透视美元局!aapoker辅助插件工具下载,wepoker辅助器是真的的吗,最新技巧(有挂透明)1、...
透视透视挂!hhpoker万能... 透视透视挂!hhpoker万能辅助器,wepoker透视脚本,推荐十款(有挂技巧);1、机器人多个强...
透视模拟器!wpk透视辅助靠谱... 透视模拟器!wpk透视辅助靠谱吗,aapoker免费透视脚本,传递经验(有挂方法)1、让任何用户在无...