import asyncio


async def gather_with_concurrency(n, *tasks):
    """
    Execute tasks concurrently with a max amount of tasks running at the same time.
    Retrieved from https://stackoverflow.com/a/61478547/7868972.
    """
    semaphore = asyncio.Semaphore(n)

    async def sem_task(task):
        async with semaphore:
            return await task
    return await asyncio.gather(*(sem_task(task) for task in tasks))