假设我们有一堆下载链接,每个链接可能需要不同的下载时间.我只允许使用最多3个连接下载.现在,我想确保使用asyncio有效地执行此操作.
这就是我想要实现的目标:在任何时候,尽量确保我至少运行3次下载.
Connection 1: 1---------7---9---
Connection 2: 2---4----6-----
Connection 3: 3-----5---8-----
Run Code Online (Sandbox Code Playgroud)
数字代表下载链接,而连字符代表等待下载.
这是我正在使用的代码
from random import randint
import asyncio
count = 0
async def download(code, permit_download, no_concurrent, downloading_event):
global count
downloading_event.set()
wait_time = randint(1, 3)
print('downloading {} will take {} second(s)'.format(code, wait_time))
await asyncio.sleep(wait_time) # I/O, context will switch to main function
print('downloaded {}'.format(code))
count -= 1
if count < no_concurrent and not permit_download.is_set():
permit_download.set()
async def main(loop):
global count
permit_download = asyncio.Event()
permit_download.set()
downloading_event = asyncio.Event()
no_concurrent = 3 …Run Code Online (Sandbox Code Playgroud) 我在我的应用程序中使用asyncio,我对将事件循环作为参数传递感到困惑.
使用事件循环编写函数/方法时有三种可能性:
asyncio.get_event_loop()asyncio.get_event_loop()似乎最后一种情况大部分时间都在使用,但即使在asyncio api中,使用也是不一致的.因为我没有缩进使用两个分离的事件循环,所以只是asyncio.get_event_loop()在需要的地方使用?
什么是最好的方式?