0

I have an iterable of coroutines which run in parallel.

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop=loop)

_lock = asyncio.Lock()

asyncio.run(apply_coroutines())

async def apply_coroutines():
    await asyncio.gather(
        coroutine1(),
        coroutine2(),
        coroutine3(),
        coroutine4(),
        )

async def another_coroutine():
    print('another method')

I have 2 conditions. the first condition triggers, say, coroutine2(). Once triggered, I have a call_later method for a future event. I need to suspend all coroutines once coroutine2() is triggered, until a condition cond2 is satisfied.

What I tried is below where I delayed 10 second the call:

async def coroutine2():
    if cond1:
        # ...
        _lock.acquire()
        loop.call_later(10, another_coroutine)
        _lock.release()
  1. how can I implement a condition cond2 in place of delaying 10 seconds?

  2. Am I right with the way I am using the Lock? Because with asyncio.gather() I have interference of coroutines. Ex: one of them starts output to IO, in a text file, but the second takes turn and finishes IO output.

  • 1
    You could write a coroutine that doesn't return until cond2 is satisfied, and simply `await that_coroutine()`. Once a lock is acquired by task A, it cannot be acquired by any other task until "A" releases it. That doesn't sound like it's anything close to what you need here. If `gather` is creating a problem, don't use it. You can call `asyncio.create_task` any time, call `task.cancel` any time, and await a task if you want to suspend one task until some other task is finished. – Paul Cornelius Feb 13 '23 at 10:32
  • 1
    https://stackoverflow.com/questions/75291756/pause-all-asyncio-tasks-in-python/75293126#75293126 – Paul Cornelius Feb 13 '23 at 10:34
  • @PaulCornelius will this be through a Future object and `.set_result()` method? – bugrahaskan Feb 13 '23 at 10:54
  • A Future is a possibility although it's very unusual that I find a need for explicitly creating one of those. I prefer to use one of the waiting primitives (Lock, Event and so on) when I need such logic. – Paul Cornelius Feb 13 '23 at 20:11
  • Does this answer your question? [Is it possible to suspend and restart tasks in async Python?](https://stackoverflow.com/q/66687549/8601760) – aaron Feb 14 '23 at 10:08

0 Answers0