Search code examples
pythonpython-asyncio

Guarantee asyncio execution order


I have seen other answers on here stating that asyncio doesn't guarantee execution order, only that the order of the outputs will match that of the inputs.

Is there a way I can guarantee the execution order

For example, if I have a list of the functions I want to run, will calling create task on each of them before calling gather work? Is there something else I can do to achieve this?


Solution

  • You could do this with asyncio.Event:

    async def perform_task(listen_event, push_event):
        await do_some_paralell_work()
        await listen_event.wait()
        await do_some_work_in_order()
        if push_event:
            await push-event.set()
    
    async def main():
        events = [asyncio.Event() for i in range(100)]
        tasks = [asyncio.Task(events[i], events[i+1] if i<100 else None) for i in range(100)]
        events[0].set()
        await asyncio.gather(*tasks)
    

    This should let the parallel work run in parallel but then run the final statement in order