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
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)
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