asyncio.run()函数是否会使用已存在的event_loop?(生产者消费者的asyncio.Queue)
创始人
2024-09-21 05:30:30
0

asyncio.run() 函数将会创建一个新的 event_loop,而非使用已存在的 event_loop。当然,您可以通过 async with 来手动传递一个 event_loop 来使用现有的 event_loop。

下面是使用 asyncio.Queue 实现生产者消费者模式的示例代码,其中 async with 用于手动传递 event_loop:

import asyncio

async def producer(queue: asyncio.Queue): for i in range(5): await asyncio.sleep(1) await queue.put(i) print(f"Producer puts {i} into queue")

async def consumer(queue: asyncio.Queue): while True: item = await queue.get() await asyncio.sleep(2) print(f"Consumer gets {item} from queue")

async def main(): my_queue = asyncio.Queue() async with asyncio.get_running_loop(): producer_task = asyncio.create_task(producer(my_queue)) consumer_task = asyncio.create_task(consumer(my_queue)) await asyncio.gather(producer_task, consumer_task)

asyncio.run(main())

相关内容

热门资讯

攻略辅助挂!aapoker怎么... 攻略辅助挂!aapoker怎么拿好牌,德扑之星有辅助软件吗,其实是有挂(有挂头条)1、全新机制【德扑...
科技通报!wepoker私人定... 科技通报!wepoker私人定制透视,wepoker插件功能辅助器,好像真的有挂(有挂详细)1、免费...
事发当天!wepoker开脚本... 事发当天!wepoker开脚本视频,德普之星透视辅助插件,竟然是有挂(今日头条)1、这是跨平台的德普...
这一问题亟待解决!wepoke... 这一问题亟待解决!wepoker私人局透视,德普之星透视辅助软件下载,一贯是有挂(有挂技巧)1、起透...
玩家必用!wepoker破解版... 玩家必用!wepoker破解版内购,hhpoker是真的吗,其实真的有挂(有挂讲解)1、上手简单,内...
2026版教学!hhpoker... 2026版教学!hhpoker怎么防作弊,德普之星辅助软件,原来真的有挂(有挂攻略)1、超多福利:超...
记者揭秘!智星德州插件,pok... 记者揭秘!智星德州插件,pokemmo脚本辅助器下载,竟然有挂(有挂讲解)1)免费钻石:进一步探索免...
截至发稿!德州透视插件,德普之... 截至发稿!德州透视插件,德普之星透视辅助软件是真的吗,一直真的是有挂(有挂教程)1、玩家可以在德普之...
一分钟揭秘!poker wor... 一分钟揭秘!poker world辅助器,哈糖大菠萝有挂吗,一贯是有挂(有挂存在)1、游戏颠覆性的策...
此事引发广泛关注!pokemo... 此事引发广泛关注!pokemomo辅助软件,德普之星透视辅助软件是真的吗,竟然是有挂(有挂秘籍)1、...