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?
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
You probably want to read the section on asyncio syncrhonization. You have have one task wait on an Event that is set by another task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With