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辅助使用教程)太嚣张了好像是真的有挂(透视)揭秘攻略(2026已更新)(哔...
黑科技能赢(德州之星app有外... 一、德州之星app有外挂吗简介了解软件请加微:136704302德州之星app有外挂吗是一款在线扑克...
黑科技教学(wepoke苹果下... 1、黑科技教学(wepoke苹果下载网址)太嚣张了从前有挂(透视)必赢教程(2021已更新)(哔哩哔...
黑科技教程(智星菠萝德州辅助工... 黑科技教程(智星菠萝德州辅助工具)太坑了都是真的是有挂(透视)细节揭秘(2021已更新)(哔哩哔哩)...
黑科技教程(微扑克职业代打)太... 黑科技教程(微扑克职业代打)太嚣张了原来真的有挂(透视)插件教程(2024已更新)(哔哩哔哩)1、用...
辅助黑科技(微扑克ai算牌器)... 辅助黑科技(微扑克ai算牌器)太夸张了原生有挂(透视)第三方教程(2020已更新)(哔哩哔哩)1、不...
黑科技ai代打(德州之星模拟器... 黑科技ai代打(德州之星模拟器)太夸张了竟然是真的有挂(透视)玩家教你(2026已更新)(哔哩哔哩)...
黑科技科技(wepokewep... 一、wepokewepoke透视挂怎么测试简介了解软件请加微:136704302wepokewepo...
黑科技ai代打(aa扑克辅助)... 黑科技ai代打(aa扑克辅助)太离谱了切实是有挂(透视)2025教程(2020已更新)(哔哩哔哩)1...
黑科技计算(wpk ai辅助)... 您好,wpk ai辅助这款游戏可以开挂的,确实是有挂的,需要了解加威信【136704302】很多玩家...