Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute 2 coroutines in Python 3.6

I cannot get two coroutines to execute in parallel in my Python 3.6 program. Here is an example:

import asyncio, time

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(start_coros())


async def start_coros():
    await coro1()
    await coro2()


async def coro1():
    print("coro1")
    time.sleep(3000)


async def coro2():
    print("coro2 - we want to get here")


if __name__ == "__main__":
    main()

As you can see, the first coroutine gets executed first but the second does not run concurrently.

Can you please give me a hint as to how to run them both simultaneously?

Thanks kindly in advance for your help

like image 571
Jenia Ivanov Avatar asked Oct 15 '22 03:10

Jenia Ivanov


1 Answers

To run two coroutines "in parallel", create Tasks:

async def start_coros():
    # ensure_future -> create_task in Python 3.7
    tasks = [asyncio.ensure_future(coro()) for coro in (coro1, coro2)]
    await asyncio.wait(tasks)

However there is a huge problem in coro1. asyncio is based on cooperative scheduling. Only one coroutine can run at a time. A scheduler switches between coroutines, but that can happen only when the running coroutine awaits something. If a coroutine spends too much time between awaits, the program appears not responsive. So avoid time.sleep()!

async def coro1():
    print("coro1")
    await asyncio.sleep(3000)
like image 133
VPfB Avatar answered Oct 19 '22 03:10

VPfB