Asyncio semaphore - concurrency limit

import asyncio


async def process(sem, i):
    async with sem:
        print("processing:", i)
        await asyncio.sleep(1)
        return i * i


async def main():
    sem = asyncio.Semaphore(value=2)  # max concurrent tasks
    items = range(5)
    tasks = [process(sem, x) for x in items]
    for task in asyncio.as_completed(tasks):
        res = await task
        print("got:", res)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())