how to add a coroutine to a running asyncio loop? how to add a coroutine to a running asyncio loop? python-3.x python-3.x

how to add a coroutine to a running asyncio loop?


You can use create_task for scheduling new coroutines:

import asyncioasync def cor1():    ...async def cor2():    ...async def main(loop):    await asyncio.sleep(0)    t1 = loop.create_task(cor1())    await cor2()    await t1loop = asyncio.get_event_loop()loop.run_until_complete(main(loop))loop.close()


To add a function to an already running event loop you can use:

asyncio.ensure_future(my_coro())

In my case I was using multithreading (threading) alongside asyncio and wanted to add a task to the event loop that was already running. For anyone else in the same situation, be sure to explicitly state the event loop (as one doesn't exist inside a Thread). i.e:

In global scope:

event_loop = asyncio.get_event_loop()

Then later, inside your Thread:

asyncio.ensure_future(my_coro(), loop=event_loop)


Your question is very close to "How to add function call to running program?"

When exactly you need to add new coroutine to event loop?

Let's see some examples. Here program that starts event loop with two coroutines parallely:

import asynciofrom random import randintasync def coro1():    res = randint(0,3)    await asyncio.sleep(res)    print('coro1 finished with output {}'.format(res))    return resasync def main():    await asyncio.gather(        coro1(),        coro1()    ) # here we have two coroutines running parallelyif __name__ == "__main__":    loop = asyncio.get_event_loop()    loop.run_until_complete(main())

Output:

coro1 finished with output 1coro1 finished with output 2[Finished in 2.2s]

May be you need to add some coroutines that would take results of coro1 and use it as soon as it's ready? In that case just create coroutine that await coro1 and use it's returning value:

import asynciofrom random import randintasync def coro1():    res = randint(0,3)    await asyncio.sleep(res)    print('coro1 finished with output {}'.format(res))    return resasync def coro2():    res = await coro1()    res = res * res    await asyncio.sleep(res)    print('coro2 finished with output {}'.format(res))    return resasync def main():    await asyncio.gather(        coro2(),        coro2()    ) # here we have two coroutines running parallelyif __name__ == "__main__":    loop = asyncio.get_event_loop()    loop.run_until_complete(main())

Output:

coro1 finished with output 1coro2 finished with output 1coro1 finished with output 3coro2 finished with output 9[Finished in 12.2s]

Think about coroutines as about regular functions with specific syntax. You can start some set of functions to execute parallely (by asyncio.gather), you can start next function after first done, you can create new functions that call others.