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

相关内容

热门资讯

透视要领!德普之星辅助器怎么用... 透视要领!德普之星辅助器怎么用(WePoKer黑科技)确实真的是有辅助软件(哔哩哔哩)1、全新机制【...
透视窍要!hardrock透视... 您好,hardrock透视工具这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
透视绝活!hhpoker德州透... 透视绝活!hhpoker德州透视挂(AApoker插件)确实是有辅助插件(哔哩哔哩)1、起透看视 h...
透视指南书!hhpoker买挂... 透视指南书!hhpoker买挂(WePoKer助手)一贯是有辅助神器(哔哩哔哩)1、hhpoker买...
透视攻略!wepoker究竟有... 透视攻略!wepoker究竟有没有透视(HHpoker有用)果然存在有辅助攻略(哔哩哔哩)wepok...
透视窍要!wepoker免费脚... 透视窍要!wepoker免费脚本咨询(WePoKer工具)都是存在有辅助插件(哔哩哔哩)1、wepo...
透视阶段!hhpoker开挂教... 透视阶段!hhpoker开挂教程(WePoKer app)竟然真的有辅助神器(哔哩哔哩)hhpoke...
透视办法!wpk辅助软件(WP... 透视办法!wpk辅助软件(WPK透视版)切实是真的有辅助技巧(哔哩哔哩)1、wpk辅助软件免费脚本咨...
透视积累!德州hhpoker是... 透视积累!德州hhpoker是真的吗(WePoKer辅助器)切实是有辅助脚本(哔哩哔哩)1、德州hh...
透视模板!德州局透视脚本(WP... 透视模板!德州局透视脚本(WPK购买)切实存在有辅助方法(哔哩哔哩)1、很好的工具软件,可以解锁游戏...