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())

相关内容

热门资讯

透视总结!德州局怎么透视(透视... 透视总结!德州局怎么透视(透视)透牌教程(2021已更新)(哔哩哔哩);德州局怎么透视软件透明挂微扑...
透视代打!aapoker怎么开... 透视代打!aapoker怎么开辅助器(透视)透视脚本下载(果然是真的有挂)1、全新机制【aapoke...
透视苹果版!竞技联盟破解版最新... 透视苹果版!竞技联盟破解版最新版(透视)曝光教程(2024已更新)(哔哩哔哩)1、玩家可以在竞技联盟...
透视攻略!aapoker免费透... 透视攻略!aapoker免费透视脚本(透视)透视方法(一贯是有挂)1、aapoker免费透视脚本系统...
透视中牌率!红龙poker有辅... 透视中牌率!红龙poker有辅助吗(透视)技巧教程(2023已更新)(哔哩哔哩)1、实时红龙poke...
透视透视挂!aapoker怎么... 透视透视挂!aapoker怎么拿好牌(透视)万能辅助器(本来有挂)1、aapoker怎么拿好牌系统规...
透视数据!约局吧德州真的有透视... 透视数据!约局吧德州真的有透视挂吗(透视)微扑克教程(2021已更新)(哔哩哔哩)1、起透看视 约局...
透视透视!pokemmo免费脚... 透视透视!pokemmo免费脚本(透视)AA德州教程(2024已更新)(哔哩哔哩);1、每一步都需要...
透视实锤!aapoker脚本怎... 透视实锤!aapoker脚本怎么用(透视)免费透视脚本(其实是真的有挂)1、玩家可以在aapoker...
透视ai!约局吧德州透视(透视... 透视ai!约局吧德州透视(透视)介绍教程(2025已更新)(哔哩哔哩)1、构建自己的约局吧德州透视辅...