首页 > 解决方案 > asyncio.gather 与列表理解

问题描述

在下面的代码中,是否get_all_details_1get_all_details_2行为相同?

async def get_details(category, limit):
    async with limit:
        # ... 

limit = asyncio.Semaphore(4)
a_list = .... # a big list

async def get_all_details_1():
    b_list = await asyncio.gather(*[get_details(x, limit) for x in a_list])
    # ....


async def get_all_details_2():
    b_list = [await get_details(x, limit) for x in a_list]
    # ....

标签: python

解决方案


绝对不!例子:

import asyncio
import time

async def slowtask():
    await asyncio.sleep(1)

async def gather():
    await asyncio.gather(*[slowtask() for _ in range(10)])

async def listcomp():
    [await slowtask() for _ in range(10)]

start = time.time()
asyncio.run(gather())
print("gather", time.time() - start)

start = time.time()
asyncio.run(listcomp())
print("listcomp", time.time() - start)

给我们:

gather 1.0030405521392822
listcomp 10.015443325042725

asyncio.gather正确地允许多个异步任务异步运行,而列表理解await一个接一个,导致有效的串行代码。


推荐阅读