[Python] Is it possible to limit the number of coroutines running corcurrently in asyncio?

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I already wrote my script using asyncio but found that the number of coroutines running simultaneously is too large and it often ends up hanging around.

    So I would like to limit the number of coroutines concurrently, and once it reaches the limit, I want to wait for any coroutine to be finished before another is executed.

    My current code is something like the following:

    loop = asyncio.get_event_loop()
    p = map(my_func, players)
    result = loop.run_until_complete(asyncio.gather(*p))

    async def my_func(player):
    # something done with `await`


    The players is of type list and contains many elements (say, 12000). It needs so much computational resource to run all of them simultaneously in asyncio.gather(*p) so I would rather like the number of players run simultaneously to be 200. Once it reaches 199, then I wish another coroutine starts to be executed.

    Is this possible in asyncio?

    Continue reading...

Compartilhe esta Página