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

相关内容

热门资讯

一分钟揭秘!福建兄弟13水辅助... 一分钟揭秘!福建兄弟13水辅助,wepoker有什么规律,规律教程(有挂方法);亲真的是有正版授权,...
重大推荐!广西老友有破解吗,竞... 重大推荐!广西老友有破解吗,竞技联盟破解版最新版,教你攻略(有挂分享);广西老友有破解吗免费下载原版...
玩家必备教程!四川皮皮辅助,w... 玩家必备教程!四川皮皮辅助,wepoker私人局外卦,技巧教程(有挂教程);1、不需要AI权限,帮助...
一分钟揭秘!情怀莆仙外挂,约局... 一分钟揭秘!情怀莆仙外挂,约局吧德州真的有透视挂吗,必胜教程(揭秘有挂);一、情怀莆仙外挂有挂的是的...
带你了解!雀友会潮汕图片辅助器... 带你了解!雀友会潮汕图片辅助器,wepoker俱乐部辅助,技巧教程(有挂详情)是一款可以让一直输的玩...
必备科技!天天微友第三方辅助软... 必备科技!天天微友第三方辅助软件下载,hhpoker辅助靠谱吗,曝光教程(有挂秘籍);1、天天微友第...
每日必备!逗娱碰胡辅助器,hh... 【福星临门,好运相随】;每日必备!逗娱碰胡辅助器,hhpoker透视方法,AI教程(的确有挂);暗藏...
玩家必看教程!微乐自建房怎么提... 玩家必看教程!微乐自建房怎么提高胜率,wepoker究竟有没有透视,科技教程(讲解有挂);玩家必看教...
玩家必备教程!微信边锋辅助下载... 玩家必备教程!微信边锋辅助下载,wepoker辅助器如何使用,安装教程(有挂方针);是一款可以让一直...
9分钟了解!天蝎辅助,hhpo... 9分钟了解!天蝎辅助,hhpoker怎么破解,揭秘教程(有挂讲解)是一款可以让一直输的玩家,快速成为...