George Y
George Y

Reputation: 535

Can I start a coroutine in Python without the blocking await?

Here is the sample code

async def washing():
  await asyncio.sleep(3)
  print("All washed!")

async def myloop():
  while 1:
    await washing() #Is there an alternative to start washing coroutine?
    print("start washing...")
    await asyncio.sleep(5)

asyncio.run(myloop())

Obviously I will get "All washed!" then "start washing..." print-out, because the await is blocking - it won't proceed until the command after it has been executed.

But what I want is the other way around, "start washing" first.

Can I just start the washing coroutine in non-blocking way and continue with the next command (e.g. print)? This is far more serious than the simple who gets printed first problem, it is about if an auxiliary coroutine can be created arbitrarily. In this blocking way, although there are two async functions, they are not running in parallel, but in sequential, and locked into effectively one coroutine forever.

Upvotes: 2

Views: 1117

Answers (1)

Artiom  Kozyrev
Artiom Kozyrev

Reputation: 3836

Just use asyncio.create_task if you want some async task to work in parallel:

import asyncio


async def washing():
    await asyncio.sleep(3)
    print("All washed!")


async def myloop():
    while 1:
        # create Task to change the app flow
        asyncio.create_task(washing())
        print("start washing...")
        await asyncio.sleep(5)


if __name__ == '__main__':
    asyncio.run(myloop())

Pay attention that if myloop will be finished before washing Task, you'll never get results of that Task.

Upvotes: 1

Related Questions