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

相关内容

热门资讯

推荐透视!pokemmo修改器... 推荐透视!pokemmo修改器手机版!总是一直都是有辅助软件(有挂方针)-哔哩哔哩推荐透视!poke...
解密透视!wepoker分析,... 解密透视!wepoker分析,sohoo竞技联盟辅助器,练习教程(有挂技巧)-哔哩哔哩1、sohoo...
必备透视!sohoopoker... 必备透视!sohoopoker辅助!总是一直都是有辅助方法(有挂方法)-哔哩哔哩1、很好的工具软件,...
总结透视!哈糖大菠萝有没有挂,... 总结透视!哈糖大菠萝有没有挂,pokemmo手机脚本辅助器,诀窍教程(证实有挂)-哔哩哔哩pokem...
专业透视!pokemmo辅助官... 专业透视!pokemmo辅助官网!其实是真的有辅助软件(有挂秘笈)-哔哩哔哩1、专业透视!pokem...
了解透视!佛手在线是不是有挂,... 了解透视!佛手在线是不是有挂,德普之星app安卓版破解版,办法教程(有挂功能)-哔哩哔哩1、下载好德...
揭露透视!哈糖大菠萝破解器!一... 揭露透视!哈糖大菠萝破解器!一贯一直总是有辅助方法(有挂神器)-哔哩哔哩1、哈糖大菠萝破解器脚本辅助...
教你透视!wepoker私局代... 教你透视!wepoker私局代打,wepoker私人局俱乐部怎么进,要领教程(有挂头条)-哔哩哔哩运...
详情透视!agpoker辅助!... 详情透视!agpoker辅助!切实是有辅助教程(有挂教程)-哔哩哔哩1、上手简单,内置详细流程视频教...
了解透视!大菠萝789辅助器下... 了解透视!大菠萝789辅助器下载,wpk透视辅助下载,妙招教程(有挂详细)-哔哩哔哩所有人都在同一条...